Reputation: 117
hi i m a beginner in java i have a doubt:
in the case for example i write a game with a server and 3 clients and since i dont need threads because clients follow a decided order and only one of them can play in its turn,
can i put the server in listening and execute some code like this :
while((i++ < maxConnections) ){
Socket connection = listener.accept();
// code that saves the "connection" to a player Object
//not closing the connection
}
tell me if i am wrong (interested in the part after the accept):
if i dont close the connection each time a create it for each client, can i write and read form the stream every time i need it ?? ( using the connection variable saved in each player object ) i ll close the connection only when the client has finished all the communication with the server
if i dont close it, the second client cannot connect? is it only possible with threads ?
sorry but i am really confused on netprogramming
Upvotes: 2
Views: 798
Reputation: 22741
The flaw in this method is that you have to receive that many listeners in order to continue on with the execution of the application. Also, you have to store them (which I can see you're doing with a Player object). What I'd do is, because the game is so small, pass the accepted socket endpoints off to new threads where they will be managed. The problem with this system is that you have no send/receive handling, so you need something to manage this without blocking up the rest of your server. You shouldn't do the sending and receiving from a socket in separate threads, manage the send and receive in the same thread, but be clever about it and don't block.
Also, I'd advise using Socket channels for the ease-of-programming this brings. A selector in this instance will tell you when a socket has data available for reading or room in the send buffer available for writing. You wait in a loop on the select() method of the selector after registering your channels with it. Apache MINA is easier as it handles the sockets and gives you asynchronous methods to work with, and it handles all this underlying stuff. You can choose to use these or wait for operations to complete, so it's quite flexible.
Upvotes: 2
Reputation: 4122
Use a thread for each connected client. Your game logic should be independent from the actual underlying technology to get data from the client to the server.
If you plan on getting serious with Game server development, RedDwarf has already everything in place for you.
Upvotes: 1