Is it better to keep a socket open for frequent requests, or to close the socket each time

StackOverflow https://stackoverflow.com/questions/20599570

  •  02-09-2022
  •  | 
  •  

Question

I'm writing a program that will do 1 GET request a second to a server. I am using a socket (QTcpSocket), and I want to know if I should include "Connection: Close" within my request and then recreate the socket for each request, or if it is better to simply keep the socket alive because I am repeating the same request once every second.

Was it helpful?

Solution

Establishing a TCP connection takes more than one round-trip. If your connection happens to be a SSL connection, there are several more round-trips. If you plan to communicate with the same destination multiple times, it probably pays off to establish a connection and use while it is still up. You should probably make your code such that sending a request is independent of the connection currently being up and have it [re-] establish a connection when needed.

OTHER TIPS

Opening a socket requires 3 packet exchanges, and closing it requires 4. You should aim to keep connections open rather than incur this overhead on every transaction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top