UdpSocket Class
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
Constructors
Initializes a new instance of the UdpSocket class on a random available port.
Initializes a new instance of the UdpSocket class, binding to the specified local port.
Sends data to a remote endpoint using the UDP protocol.
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.");
}
byte[] data: The data to send.EndPoint remoteEndPoint: The remote endpoint to send the data to.
ArgumentNullException: data is null.SocketException: An error occurred while sending data.
Receives data from a remote endpoint.
byte[] buffer: The buffer to store the received data.
ArgumentNullException: buffer is null.SocketException: An error occurred while receiving data.
Binds the UDP socket to a local endpoint.
EndPoint localEndPoint: The local endpoint to bind to.
ArgumentNullException: localEndPoint is null.SocketException: An error occurred while binding the socket.
Closes the UDP socket connection.
Properties
Gets the local endpoint to which the UDP socket is bound.
Gets the remote endpoint to which the UDP socket is connected (if connected).
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.