Search code examples
javasocketstcpduplex

java socket sending and receiving


since hours I am thinking about how I should use Java Sockets to send and receive data. I hope you can help me finding a good way to do it.

I have build a Server/Client structure where the client connects to the server and gets his own thread handling a request-response method. The information are capsuled in XML.

At the beginning the Server starts a blocking socket read. First I use writeInt() where the lenght of the XML message is transmitted. After that the Server reads the amount of lenght bytes and parses the message. After the transmission the client goes in the receive state and waits for an response.

That is fine but after the client authenticates the server waits for the things that will come and blocks.

But what should I do when the server has no information which needs to be transmitted. I could try to destroy the read blocking and send the message to the client. But what happens if the client comens in mind that he has also a message and also begins to send. In that moment no one will listen.

For that maybe I could use some sort of buffer but I have the feeling that this is not the way I should go.

I have been searching for a while and found some interesting information but I didn't understand them well. Sadly my book is only about this simple socket model.

Maybe I should use two threads. One sending and one receiving. The server has a database where the messages are stored and waiting for transmission. So when the server receives a message he stores that message in the database and also the answer like "message received" would be stored in the database. The sender thread would look if there are new messages and would send "message received" to the client. That approach would not send the answer in millisenconds but I could image that it would work well.

I hope that I gave you enough information about what I am trying. What would you recommend me how to implement that communication?

Thanks


Solution

  • But what should I do when the server has now information which needs to be transmitted.

    I would make writes from the server synchronized. This will allow you to respond to requests in one thread, but also send other messages as required by another thread. For the client you can have a separate thread doing the receiving.

    A simpler model may be to have two sockets. One socket works as you do now and when you "login" a unique id is sent to the client. At this point the client opens a second connection with a dedicated thread for listening to asynchronous events. It passes the unique id so the server know which client the asynchronous messages are for.

    This will give a you a simple synchronous pattern as you have now and a simple asynchronous pattern. The only downside is you have two socket connections and you have co-ordinate them.