Search code examples
c#udpudpclient

UDP - "ConnectAndSend vs SendTo"


I am writing code for a simple C# library responsible for managing UDP communication in a client/server architecture.
I based my communication on C# System.Net.Sockets.UdpClient class, both for the server-side and for the client-side; for the sending feature of the client-side, I saw there are two possible options:

  1. perform a single call to Connect(IPEndPoint endPoint) to specifiy target endpoint, then perform subsequent calls to Send(byte[] dgram, int bytes), hence without specifying target endpoint
  2. always perform calls to Send(byte[] dgram, int bytes, IPEndPoint endPoint), hence specifying target endpoint

regarding first option, if a different target endpoint is required, simply perform a new call to Connect.

I've looked at the MSDN, but still a couple of questions remained unanswered:

  • are there any advantages choosing between one option and the other one? technically the first one seems to me more clean and clear, but the second one gives you this benefit "If you call the Connect method, any datagrams that arrive from an address other than the specified default will be discarded"
  • in particular, are there any performance reasons to choose among them? again, the first one seems to me more optimized.
  • why providing two different ways of achieving almost the same functionality (if not exactly the same)?

Solution

  • The slight differences between the two approaches I was able to find are:

    1. Connect(IPEndPoint endPoint) with Send(byte[] dgram, int bytes) restricts the client to send data exclusively to the end point it is connected to and implies any datagrams that arrive from an address other than the specified default will be discarded.

    2. Send(byte[] dgram, int bytes, IPEndPoint endPoint) allows to send data to different end point at each call, without need to perform a reconnection.