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

3.3k views Asked by At

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.

2

There are 2 answers

0
Dietmar Kühl On BEST ANSWER

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.

0
user207421 On

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.