Reputation: 1769
Using TCP, the workflow for sending the data is following:
- open socket()
- write(data1)
- write(data2)
- write ... data n
- close(socket)
But how is it with UDP? Do we keep the socket open? Or do we open the socket every time the data is ready? What is the best practice for that?
- open socket();
- write(data1);
- close(socket);
- open socket();
- write(data2);
- close(socket);
Upvotes: 1
Views: 2123
Reputation: 3360
Opening a TCP socket usually means
and closing a TCP socket means
Opening a UDP socket does not trigger any network communication and it only creates a socket structure in OS.
Opening a TCP socket is more costly that opening a UDP socket because opening and closing a TCP socket creates a TCP session whereas opening and closing a UDP socket is a local action only.
It is best practice to reuse existing UDP socket for sending/receiving more than one datagram. It is useless to close a UDP socket if it can be reused for later communication. Moreover if the application closed the UDP socket then incoming traffic to port, that was bound to the socket, would be lost.
Upvotes: 1
Reputation: 810
Yes, it makes sense keep the socket open if you have more to send (or receive).
Upvotes: 0