0

I'm implements a fairly simple server that can should handle multiple clients, and I first accepting clients as such

    private static Queue<Player> playerList = new ArrayDeque<Player>(); 

    try {
        serverSocket = new ServerSocket(port);

        // Listen for new clients 
        Socket clientSocket = null;
        int numPlayers = 0;

        while (numPlayers < 2){
            clientSocket = serverSocket.accept();

            if(clientSocket != null){
                // Create a new player 
                Player p = new Player(clientSocket);
                // Add them to the list of players
                playerList.add(p);
            }

        }
    } 
    catch (IOException e) {
        System.out.println("Could not listen on port: " + port);
        System.exit(-1);
    }   

From what I have read it seems like there is usually a new thread created for each client, but I don't really see the need to go through this trouble if there is a simpler way. I simply need to be able to send and receive messages between the server and clients.

while (true) {
    // Check for anything on the buffer

        // Parse message

}

So is there an easy way to just

Listen for incoming messages

Determine which client the message is coming from

Parse the message etc.

All in a loop without creating a separate thread for each client?

4

2 回答 2

1

它可以工作。服务器正在处理当前请求时,并发请求将处于等待状态。但是您需要确保客户端准备好处理 ConnectException 并重复请求。传入连接队列有限制(默认为 50,可以更改)。如果队列已满,ServerSocket 将拒绝连接。请参阅 ServerSocket API

顺便说一句 if(clientSocket != null) 没有意义, serverSocket.accept() 永远不会返回 null

于 2013-06-01T02:22:37.790 回答
1

尝试使用这样的东西:

while (true) {
    for(Player p : playerList) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getSocket().getInputStream()));
        String data;
        while ((data = reader.readLine() != null) {
            p.packetRecieved(data);
        }
    }
}
于 2013-06-01T02:26:54.073 回答