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

前端 未结 2 553
灰色年华
灰色年华 2021-01-13 13:08

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

相关标签:
2条回答
  • 2021-01-13 13:40

    That depends. Creating a new socket means two computers have to discover each other, so there is name lookup, TCP/IP routing and resource allocation involved. Not really cheap but not that expensive either. Unless you send data more than 10 times/second, you won't notice.

    If you keep a socket open and don't send data for some time, a firewall between the two computers will eventually decide that this connection is stale and forget about it. The next data packet you send will fail with a timeout.

    So the main difference between the two methods is whether you can handle the timeout case properly in your code. You will have to handle this every time you write data to the socket.

    In many cases, the code to write is hidden very deep somewhere and the code doesn't actually know that it's writing to a socket plus you will have more than one place where you write data, so the error handling will leak into your design. That's why most people prefer to create a new socket every time, even if it's somewhat expensive.

    0 讨论(0)
  • 2021-01-13 13:56

    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.

    0 讨论(0)
提交回复
热议问题