Václav Struhár
Václav Struhár

Reputation: 1769

Keeping socket open for UDP?

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

Answers (2)

Zaboj Campula
Zaboj Campula

Reputation: 3360

Opening a TCP socket usually means

  • create a socket structure in operating system
  • establish a TCP connection (3 way handshake with a peer)

and closing a TCP socket means

  • TCP connection release
  • delete socket structure in operating system

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

ewindes
ewindes

Reputation: 810

Yes, it makes sense keep the socket open if you have more to send (or receive).

Upvotes: 0

Related Questions