我正在尝试编写简单的服务器客户端聊天解决方案。出于测试目的,我创建了一个由 2 个 serverThreads 组成的数组,它们负责从连接的客户端发送和接收消息。
我希望服务器在连接的客户端数量达到最大值后拒绝连接。然而,即使服务器不接受连接,客户端的套接字也会被创建。方法socket.isBound和isConnected都返回true值。
回到主要问题。 当 ServerSocket 无法 .accept() 附加连接时,您有什么想法如何拒绝客户端连接吗?
这是服务器类的代码。
public class Server {
private ServerSocket serverSocket = null;
private ServerThread serverThread[] = new ServerThread[2];
protected volatile int clientCount = 0;
public Server (int port){
try {
System.out.println("Binding to port " + port + " ...");
serverSocket = new ServerSocket (port);
System.out.println("Binded to port " + port + ".");
} catch (IOException e) {
System.out.println("Failed binding to the port: " + e.getMessage());
}
}
public void addThread (Socket socket){
System.out.println ("Client connected at socket: " + socket);
serverThread[clientCount] = new ServerThread (this, socket);
try {
serverThread[clientCount].open();
serverThread[clientCount].start();
} catch (IOException e) {e.getMessage();}
}
public void waitForClient () {
boolean isLogPrinted = false;
while (true){
try {
if (clientCount < serverThread.length){
System.out.println ("Waiting for connection...");
isLogPrinted = false;
addThread (serverSocket.accept());
clientCount++;
System.out.println("Client count: " + clientCount);
}
else {
if (!isLogPrinted){
System.out.println("MAXIMUM NUMBER OF CLIENTS REACHED! (" + clientCount + ").");
isLogPrinted = true;
}
}
} catch (IOException e) {
System.out.println("Error while waiting for new clients to connect: " + e.getMessage());
}
}
}
public synchronized void broadcastMessages (String msg){
for (int i = 0; i < clientCount; i++)
serverThread[i].sendMessage(msg);
}
public static void main (String args[]){
Server server = new Server (4200);
server.waitForClient();
}
}
最佳答案
I'd like a server to reject a connections after the number of connected clients reach a maximum value.
关闭服务器套接字。
However, even though the server do not accept the connection, the socket on client side is created. Methods
socket.isBound
andisConnected
both return true value.
正确。这是因为 TCP 维护着一个传入连接的“积压队列”,这些连接已完成但尚未被服务器应用程序接受。
So back to the main question. Do you have any ideas how could I reject the client from connecting when the ServerSocket will not be able to .accept() additional connection?
当连接数达到最大时关闭服务器套接字。
然而,由于积压,这项技术永远不可能完美。没有完美的解决方案。您可以让服务器立即关闭多余的连接,但多余的客户端在尝试发送内容之前不会检测到这一点。如果您需要完美,您可能必须引入一个应用程序协议(protocol),服务器相应地发送“已接受”或“已拒绝”等内容。
关于Java - 如何检查 ServerSocket.accept() 是否连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40197514/