UdpSocket Class

Namespace: System.Net.Sockets
Assembly: System.Net.Primitives

Provides support for User Datagram Protocol (UDP) sockets. UDP is a connectionless transport protocol that offers a streamlined datagram and data stream delivery service.

Syntax

public class UdpSocket : IDisposable
UdpSocket()

Initializes a new instance of the UdpSocket class on a random available port.

UdpSocket(int port)

Initializes a new instance of the UdpSocket class, binding to the specified local port.

Send(byte[] data, EndPoint remoteEndPoint)

Sends data to a remote endpoint using the UDP protocol.

Example:

using System.Net;
using System.Net.Sockets;

byte[] message = System.Text.Encoding.ASCII.GetBytes("Hello UDP!");
IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);

using (UdpSocket socket = new UdpSocket())
{
    socket.Send(message, remoteIpEndPoint);
    Console.WriteLine("Message sent.");
}
                            
Parameters:
  • byte[] data: The data to send.
  • EndPoint remoteEndPoint: The remote endpoint to send the data to.
Returns: The number of bytes sent.
Exceptions:
  • ArgumentNullException: data is null.
  • SocketException: An error occurred while sending data.
Receive(byte[] buffer)

Receives data from a remote endpoint.

Parameters:
  • byte[] buffer: The buffer to store the received data.
Returns: The number of bytes received.
Exceptions:
  • ArgumentNullException: buffer is null.
  • SocketException: An error occurred while receiving data.
Bind(EndPoint localEndPoint)

Binds the UDP socket to a local endpoint.

Parameters:
  • EndPoint localEndPoint: The local endpoint to bind to.
Exceptions:
  • ArgumentNullException: localEndPoint is null.
  • SocketException: An error occurred while binding the socket.
Close()

Closes the UDP socket connection.

Properties

LocalEndPoint

Gets the local endpoint to which the UDP socket is bound.

RemoteEndPoint

Gets the remote endpoint to which the UDP socket is connected (if connected).

Available

Gets the number of bytes available to be read from the socket.

Implements

Remarks

The UdpSocket class provides a low-level interface for sending and receiving UDP datagrams. It is suitable for applications that require fine-grained control over network communication or need to implement custom protocols. For higher-level UDP abstractions, consider using classes like UdpClient.