对于每个客户端,你需要启动单独的线程。例:
public class ThreadedEchoServer { static final int PORT = 1978; public static void main(String args[]) { ServerSocket serverSocket = null; Socket socket = null; try { serverSocket = new ServerSocket(PORT); } catch (IOException e) { e.printStackTrace(); } while (true) { try { socket = serverSocket.accept(); } catch (IOException e) { System.out.println("I/O error: " + e); } // new thread for a client new EchoThread(socket).start(); } }}
和
public class EchoThread extends Thread { protected Socket socket; public EchoThread(Socket clientSocket) { this.socket = clientSocket; } public void run() { InputStream inp = null; BufferedReader brinp = null; DataOutputStream out = null; try { inp = socket.getInputStream(); brinp = new BufferedReader(new InputStreamReader(inp)); out = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { return; } String line; while (true) { try { line = brinp.readLine(); if ((line == null) || line.equalsIgnoreCase("QUIT")) { socket.close(); return; } else { out.writeBytes(line + "nr"); out.flush(); } } catch (IOException e) { e.printStackTrace(); return; } } }}
你还可以使用更高级的解决方案,该解决方案使用NIO选择器,因此你不必为每个客户端创建线程,但这要复杂一些。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)