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?