我试图找到这个问题的确切解决方案,但我找不到它
我已经编写了一个while循环来接受服务器程序中的客户端套接字
因为这个我无法关闭serversocket,因为它总是在监听
这是我的服务器代码
public class nserver {
public static void main(String[] args) throws IOException {
int port=4413;
//server is running on port
try(ServerSocket ss = new ServerSocket(port)){;
// socket accepts data from the incoming clients
while(true){
Socket socket = ss.accept();
// id I don't put the if case then this loop never breaks and
// although I wrote ss.close() - it will never reached - so use if case
if(socket.equals(null))
break;
System.out.println("Server is running on port "+port);
//socket.getInetAddress gives address of client ip not the server ip as the socket is mada as client socket
System.out.println("server recieved connection from "+socket.getInetAddress()+" : "+socket.getPort());
//create two threads to send and receive from client
rxClientData rx = new rxClientData(socket);
Thread t = new Thread(rx);
t.start();
sdServerData sd = new sdServerData(socket);
Thread t2 = new Thread(sd);
t2.start();
// if I put ss.close() here then it will accept only one client socket and serversocket will be closed after this line
}
ss.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
如何在客户端套接字请求后关闭serversocket,我有3个客户端
使用for循环我将有一个no.of客户端套接字的限制,但服务器应该接受这么多no.of请求 - 所以我使用while循环
对于服务器我们是否需要在现实世界中保持serverocket打开? - 以便它始终接受客户请求