Winsock ~ Creating an UDP Listener (Multiple vs 1 socket)

2.3k Views Asked by At

Dear Stackoverflowers,

I am researching networking a bit and I decided I'd like to create a small and simple networking library with Winsock. (I am using Completion Ports and Overlapped IO though)

As I researched a bit I came to the following steps for a TCP Listener(Correct me if I am wrong):

  1. Create a Listening Socket
  2. Bind it to a port/IP
  3. Listen on it
  4. When a new connection is created, give a seperate Socket for that connection.
  5. Listener continue's to listen, the specific connection is handled as needed.

EDIT: With a 'connection' from here I mean communication between the server and distinct clients.

Though for an UDP Listener we need to make use of WSARecvFrom which returns the IP address at the lpFrom parameter. Now I was wondering the following:

Is it better to make one UDP Socket listen to incoming connections on a specific port with WSARecvFrom and create new sockets for every specific connection? Or could I just use the UDP Socket itself with WSASendTo. Would that cause any performance penalties if one UDP Socket is used for for example 1000 connections? Or would it be the same or even better then creating/duplicating seperate Sockets for each different incoming connection?

Note: If multiple sockets are needed how would you handle sockets listening on the same port or could a client accept UDP from different ports?

Hope you guys can help!

Ps. Extra tips are always welcome!

1

There are 1 best solutions below

5
On BEST ANSWER

Unlike TCP, UDP is connection-less, and as such you don't need to create separate sockets for each party. One UDP socket can handle everything. Bind it to a local IP/Port and call WSARecvFrom() once, and when it reports data to your IOCP you can process the data as needed (if another thread if needed) and then call WSARecvFrom() again. Each time new data arrives, you have to look at the reported lpFrom address to know the IP/Port of the sender. And yes, you can use the same UDP socket for sending data to each sender when needed.