Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is a larger overhead: Creating a new socket each time or maintaining a single socket for data transfer

Which is the best method for sending a data using sockets:

Method 1: Creating a new socket every time when data needs to be sent and closing it when the transfer is complete.

Method 2: Using the same socket instead of creating a new socket and maintaining the connection even when waiting for new data.

like image 635
amitasviper Avatar asked Mar 17 '23 00:03

amitasviper


1 Answers

It depends on the kind of socket, but in the usual cases it is better to keep the socket unless you have very limited resources.

  • UDP is connectionless, that is you create the socket and there is no delay because of connection setup when sending a packet. But there are still system calls involved and allocating memory etc, so it is cheap but not free.
  • TCP instead needs to establish the connection before you can even start to sending data. How fast this is done depends on the latency, i.e. fast on local machine, slower in local network and even slower on the internet. Also, connection start slowly because the available bandwidth is not known yet.
  • With SSL/TLS on top of TCP connection setup is even more expensive because it needs more round trips between client and server.

In summary: If you are using TCP you almost always better keep the socket open and close it only if you lack the necessary resources to keep it open. A good compromise is to close the socket as long as you have enough activity on the socket. This is the approach usually done with HTTP persistent connections.

like image 93
Steffen Ullrich Avatar answered Apr 27 '23 01:04

Steffen Ullrich