Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I close a socket (TCPIP) after every transaction?

Tags:

c#

tcp

sockets

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();
like image 383
Jess Avatar asked Sep 16 '10 05:09

Jess


People also ask

When should I close TCP socket?

A TCP socket that is connected should not be closed until the connection has been shut down.

Should you close a socket after performing operations?

You should definitely close sockets if possible when you are done with them!

Should you close a socket Java?

The finalize() method is called by the Java virtual machine ( JVM ) before the program exits to give the program a chance to clean up and release resources. Multi-threaded programs should close all Files and Sockets they use before exiting so they do not face resource starvation.

Does server need to close socket?

The answer is yes. The reason is that accept() allocates memory, close() frees that memory.


1 Answers

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).

like image 155
Insomniac Avatar answered Oct 19 '22 22:10

Insomniac