10

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

Lets say I have some type of interprocess communication that works using sockets.

Should my processes establish a connection and hold it open (1 thread per client or similar) sending data when it needs; or is a better approach to simply establish a connection, send the data I wish, close it and enter my wait state again?

What is usually the approach to this problem?

Community
  • 1
  • 1
Maxim Gershkovich
  • 42,124
  • 39
  • 134
  • 227
  • Just out of curiosity, why sockets over named pipes? – Akash Kava Apr 13 '11 at 05:24
  • In my case I am building a bridge between an Android application and C# so I don't think pipes would be appropriate (or possible)? – Maxim Gershkovich Apr 13 '11 at 05:31
  • Interprocess refers to communication between different processes on same machine, so I asked, if they are on different machines then client server or peer to peer is correct word. – Akash Kava Apr 13 '11 at 05:39

3 Answers3

7

I asked this same question and all three responses said to leave it open. I went with that, and it seems to be working for me.

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

Community
  • 1
  • 1
Jess
  • 2,883
  • 2
  • 25
  • 38
3

Local sockets do not have much overhead since they skip the TCP/IP Stack and are implemented using named pipes. Keeping a socket open and close wouldn't make much of difference.

Muhammad Hasan Khan
  • 33,106
  • 14
  • 80
  • 125
  • 1
    Local sockets skips the TCP/IP stack only if you specifically open a Unix domain socket - where that is available. – gby Apr 13 '11 at 05:15
2

Any resource, be it file, socket, database connection or hardware device, take time and uses processor and memory to open because it has to fetch resources, compute security access and do some bookkeeping.

Opening and closing between every message will just waste CPU and memory resources.

Keeping it open for long time is also dangerous as well but you have to leave it open and decide best timeout value to close it automatically when any one end has died.

Akash Kava
  • 37,127
  • 20
  • 114
  • 162