Socket 编程 - 多个客户端

在Socket编程 - 单个客户端中,服务端只支持单个客户端的连接请求。

如果有多个客户端连接呢?需要有一个线程一直监听客户端请求,收到请求后分发给其它的线程处理。这和jetty的处理方式类似。只需要改动服务端的代码就可以了。

服务端:

public class MyMultiClientsServer {
private static final int SERVER_PORT = 4451;
ServerSocket server;
Socket socket;

public MyMultiClientsServer() {
try {
server = new ServerSocket(SERVER_PORT);

while (true) {
socket = server.accept();
new DispatchRequestThread(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Release the resources opened
}
}

class DispatchRequestThread extends Thread {
BufferedReader in;
PrintWriter out;
Socket socket;

public DispatchRequestThread(Socket socket) {
this.socket = socket;
}

@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);

while (true) {
String str = in.readLine();
System.out.println(socket.getPort() + ": " + str);
out.println("Received: " + str);

if (str.equals("end"))
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Release the resources opened
}
}
}

public static void main(String[] args) {
new MyMultiClientsServer();
}
}


开启服务端后,开启多个服务端进行测试, 结果如下:
3014: hello
3015: signature
3014:end

你可能感兴趣的:(java)