tags:

views:

50

answers:

3

I have written a TCPIP server that implements a FileSystemWatcher and fills a queue with data parsed from new files acquired by the FSW.

A single client will connect to this server and ask for data from the queue (no other client will need to connect at any time). If no data exists, the client will wait (1 second) and try again.

Both client and server are written asynchronously - my question is: should the client create a new socket for each transaction (inside the while loop), or just leave the socket open (outside the while loop)?

client.Connect()

while(bCollectData)
{
    ... communicate ...

    Thread.Sleep(1000);
}

client.Shutdown(SocketShutdown.Both);
client.Close();
A: 

I would leave the socket open outside the loop, reconnecting every iteration seems like a waste of resources.

Daniel
A: 

I would not close the socket. Every time you connect you have some handshake.

chriszero
+2  A: 

I would suggest you to leave socket open and even better to block it on the server, so that you didn't have to do Thread.Sleep. When the server will have some data he will send the message to the client.

The code will look something like this

while(bCollectData)
{
   _socket.recv(...); //this line will wait for response from server
   //... process message and start another wait in the next iteration.
}

using this approach you will get all messages immediately and avoid unneeded messages sent between client and server(the messages which return that server has no data).

Kirill Muzykov