user1875195
user1875195

Reputation: 988

Networking server with multiple clients in java

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?

Upvotes: 0

Views: 559

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

It can work. Concurrent requests will be waiting while the server is processing the current request. But you need to make sure that clients are prepared to process ConnectException and repeat a request. There is a limit for incoming connection queue (50 by default, may be changed). ServerSocket will refuse the connection if the queue is full. See ServerSocket API

BTW if(clientSocket != null) does not make sense, serverSocket.accept() never returns null

Upvotes: 1

user1779715
user1779715

Reputation:

Try using something like this:

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);
        }
    }
}

Upvotes: 1

Related Questions