java socket 服务端如何判断有没有新客户端加入
try {
ServerSocket serverSocket = new ServerSocket(88888);
Socket socket = serverSocket.accept();
if(socket != null){
System.out.println("链接的用户ip="+socket.getInetAddress());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这一段代码一运行,会阻塞在serverSocket.accept();当一有客户连接,马上会返回一个包含客户端信息的socket
你这个代码一次只能接受一个客户端,多个就不起作用了额!
写好点应该这样,不会只有一次,因为有个while(true),只要你不停,一直可以接受请求的。public class TCPServer {
ExecutorService threadPool = Executors.newCachedThreadPool();
public TCPServer(int port) {
init(port);
}
private void init(int port) {
try {
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
Socket socket = serverSocket.accept();
if (socket != null) {
threadPool.execute(new ProcessRunnable(socket));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new TCPServer(8888);
}
class ProcessRunnable implements Runnable {
public ProcessRunnable(Socket socket) {
System.out.println(socket.getInetAddress().toString());
}
public void run() {
}
}
}