I am developing a connection part of the project which will deal with various services provided to mobile devices. I need the server to be able to handle thousands of clients simultaneously.
In order to make servers life easier I am thinking weather it would be possible to make everything like this:
1. Server listens for clients
2. Client connects to the server
3. Server then adds client's Socket to the list (hashtable) of active/connected clients along with clients ID and no longer listens on that Socket (Client is listening on it's socket everytime)
4. When server has some information that needs to be sent to the client he looks up the corresponding socket (using the client ID) and sends the data.
To make sure that the clients are online server sends a ping every 10 minutes or so... If the client does not respond then server removes it from the list...
The need here is to keep the communication rate between server and clients as low as possible...
Now while I was trying to implement this idea I encountered the following difficulties:
While the server has its PrintWriter open (used to send messages to the client) the client blocks on the BufferedReader.readLine() method. However as soon as I close the PrintWriter on the server side the client is not blocking anymore- it then reads a string that is null. And since I have an infinite loop the thread keeps reading null and uses 50% of the cpu. I have made the following correction but I am not sure if it is a good idea...
String s = bufferedReader.readLine();
So can anyone suggest me a good strategy for the described scenario?
Is there a method to establish a connection with a client. Close that socket and put it to the list and when need arises temporarily open that socket, send some information and close it again to keep the communication between the endpoints to it's minimum.
The client could listen to it's socket every time...
There's several options:
1. use one connection per request. This is how HTTP works. The Java TCP library actually keeps a persistent connection under the covers, so this isn't as much a performance hit as it sounds.
2. use a persistent connection and create a protocol which delineates the start and end of messages and data. FTP is an example of this kind of protocol.
3. Use RMI. RMI (remote method invocation) wraps the ugly details of dealing with sockets in a clean object-oriented interface. This lets you focus on solving the problem you are working on rather than trying to figure out low-level socket protocols.