Sockets and Synchronization

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iLL
    New Member
    • Oct 2006
    • 63

    Sockets and Synchronization

    Okay, so I'm tying to get use to programming with sockets, and I have run into a bit of a snag.


    As of now, my program basically works like this:

    Server: Listen for a connection
    Client: Request a connection
    Server: Accept connection
    Client: Send message
    Client: Wait for response
    Server: Processes message
    Server: Send response

    I want my client to also listen for message from the server. And these message can happen at any time. When you do something like:

    Code:
    ...
    public final void listen(Socket s)
    {
    	InputStream in = s.getInputStream();
    	int aByte;
    	while((aByte=in.read())!=-1)
    	{
    		//Do stuff
    	}
    }
    ...
    The read blocks until until something can be read. This is a desired effect. However, I would like to prevent the listening thread from waking so that I can send a message and get the response without that while loop picking it up.

    Is there any way to guarantee that?

    I could open up two connections, one for sending and one for receiving. Is that frowned upon? It seems like a wast of resources.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    A socket is not a verty heavy weight resource; open two sockets: one for the server to push messages to a client and one for normal client/server communication. The client should have a separate thread reading from the first socket (it'll block when the server doesn't send anything).

    kind regards,

    Jos

    Comment

    • iLL
      New Member
      • Oct 2006
      • 63

      #3
      I think I'll give that a shot.

      I got it working by blocking threads... But it caused communication to be about 20% slower.

      Thanks for the reply.

      Comment

      Working...