-->

IPC: Connect for each request or keep socket open?

2019-05-06 04:27发布

问题:

I am planning to use sockets (local TCP) to communicate between two processes (running locally). One process will act as a server, but both processes send messages to each other asynchronously. Should I keep the socket connection open for the lifetime of the processes, or re-connect for each request?

Are there any problems that may occur if I keep a local socket open?

回答1:

Keep the socket open.

Its the simpler option and you don't incur in the overhead of opening a new socket (from the client point of view) or accepting a new client (from server point of view).



回答2:

If it's just one client, then you should keep the socket open but be ready to reconnect in case of error (the user could have reset network interfaces for example, so connection is not guaranteed to be alive). If you have many clients, use disconnection after inactivity timeout of certain time. This will let you get rid of inactive, hung or "lost" (the ones that passed away but there was no signal about socket closing form them) clients.