Gửi bởi
Quy_ny
Bên server bạn phải tạo 1 thread chính chờ các client kết nối vào.
Sau khi có client kết nối vào thì tạo 1 thread phụ chờ nhận dữ liệu (khởi tạo hàm truyền nhận data - bất đồng bộ).
Khi client ngắt kết nối sẽ xảy ra lỗi ở thread phụ này lúc này server bắt lỗi và thông báo về cho các client còn lại.
Bạn nên trình bày code theo quy định diễn đàn nhé.
Chúc may mắn.
mình trình bày cụ thể hơn chút
ở server mình có classs MainMultiThread là thread chính để lắng nghe client
Mã:
public class MainMultiThread { // Declaration section: // declare a server socket and a client socket for the server // declare an input and an output stream static Socket clientSocket = null; static ServerSocket serverSocket = null; // This chat server can accept up to 100 clients' connections static clientThread t[] = new clientThread[100]; public static void main(String args[]) { // The default port int port_number=2222; if (args.length < 1) { System.out.println("Usage: java MultiThreadChatServer
" + "Now using port number="+port_number); } else { port_number=Integer.valueOf(args[0]).intValue(); } // Connect socket try { serverSocket = new ServerSocket(port_number); } catch (IOException e) { System.out.println(e); } //Connect database connectDB con=new connectDB(); con.ConnectMySQL("smas","root","abc@123"); // Listening socket while(true){ try { clientSocket = serverSocket.accept(); for(int i=0; i<=99; i++){ if(t[i]==null) { System.out.println("new client connected"); (t[i] = new clientThread(clientSocket,t,i)).start(); break; } } } catch (IOException e) { System.out.println(e); } } }}
Mỗi client kết nối đến sẽ được quản lý bởi thread phụ clientThread
Mã:
class clientThread extends Thread{ DataInputStream is = null; PrintStream os = null; Socket clientSocket = null; clientThread t[]; int myI; boolean connected = true; public TestClient objTestClient = new TestClient(); public clientThread(Socket clientSocket, clientThread[] t, int myI){ this.clientSocket=clientSocket; this.t=t; this.myI=myI; } public void run() { String strFromClient = ""; try{ is = new DataInputStream(clientSocket.getInputStream()); os = new PrintStream(clientSocket.getOutputStream()); while (connected) { try{ strFromClient = is.readLine(); if (strFromClient == null) { System.out.println("Client Disconnected!"); connected = false; } else { System.out.println("String from client: "+ strFromClient); } } catch(java.net.SocketTimeoutException e) { System.out.println("Timed out trying to read from socket"); } } } catch(IOException e){ System.out.println("FAIL"); }; }}
Như thế đã đúng quy trình bạn nói rồi đúng ko? nhưng mình tắt client vẫn ko thấy server in ra gì hết ! bạn có thể edit giúp mình được ko ?
Pallet nhựa Lâm Đồng giải pháp hoàn hảo cho nhà kho Pallet nhựa Lâm Đồng là một giải pháp đa năng và hiệu quả trong việc vận chuyển và lưu trữ hàng hóa. Trong đó, pallet nhựa Lâm Đồng không chỉ đáp...
Pallet nhựa Lâm Đồng giải pháp...