UdpListener Class
Listens for incoming UDP datagrams on a specified port.
The UdpListener class provides a simple way to listen for incoming User Datagram Protocol (UDP) datagrams on a specific port on the local computer. It is part of the System.Net.Sockets namespace.
Constructors
UdpListener(Int32 port)
Initializes a new instance of the UdpListener class and binds it to the specified local port.
Parameters
port: int - The local port on which to listen for UDP datagrams.
UdpListener(IPEndPoint localEP)
Initializes a new instance of the UdpListener class and binds it to the specified local endpoint.
Parameters
localEP: IPEndPoint - An IPEndPoint instance that specifies the local IP address and port to bind to.
Methods
Start()
Starts listening for incoming UDP datagrams.
Remarks
This method must be called before any asynchronous or synchronous receive operations can be performed.
Stop()
Stops listening for incoming UDP datagrams.
Receive()
Receives a UDP datagram.
Remarks
This is a synchronous method. It blocks the calling thread until a datagram is received.
Return Value
byte[] - A byte array containing the received UDP datagram data.
ReceiveFrom(EndPoint remoteEP)
Receives a UDP datagram and the endpoint of the sender.
Remarks
This is a synchronous method. It blocks the calling thread until a datagram is received.
Parameters
remoteEP: out EndPoint - When this method returns, contains an EndPoint instance representing the sender's network endpoint.
Return Value
byte[] - A byte array containing the received UDP datagram data.
BeginReceive(AsyncCallback callback, Object state)
Begins an asynchronous receive operation.
Parameters
callback: AsyncCallback - An AsyncCallback delegate that references the method to call when the operation is complete.state: object - A user-defined object that contains information about the asynchronous operation. This parameter is passed to the callback delegate.
Return Value
IAsyncResult - An IAsyncResult instance that references the asynchronous operation.
EndReceive(IAsyncResult asyncResult)
Ends an asynchronous UDP datagram receive operation.
Parameters
asyncResult: IAsyncResult - The IAsyncResult returned by a call to BeginReceive.
Return Value
byte[] - A byte array containing the received UDP datagram data.
Properties
LocalEndpoint
Gets the local endpoint to which the UdpListener is bound.
Client
Gets the underlying socket for the UdpListener.
Example
The following example demonstrates how to create and use a UdpListener to receive UDP datagrams.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class UdpReceiver
{
private UdpClient udpClient;
private bool isListening = false;
public void StartListening(int port)
{
try
{
udpClient = new UdpClient(port);
isListening = true;
Console.WriteLine($"Listening on port {port}...");
// Start a new thread to handle receiving data
Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
receiveThread.Start();
}
catch (Exception e)
{
Console.WriteLine($"Error starting listener: {e.Message}");
}
}
private void ReceiveData()
{
while (isListening)
{
try
{
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
byte[] receivedBytes = udpClient.Receive(ref remoteEP);
string receivedMessage = Encoding.ASCII.GetString(receivedBytes);
Console.WriteLine($"Received from {remoteEP}: {receivedMessage}");
}
catch (SocketException sockEx)
{
if (isListening) // Only log if we're supposed to be listening
{
Console.WriteLine($"Socket Exception: {sockEx.Message}");
}
break; // Exit loop on socket errors if not explicitly stopped
}
catch (Exception e)
{
Console.WriteLine($"Error receiving data: {e.Message}");
}
}
Console.WriteLine("Receive thread stopped.");
}
public void StopListening()
{
isListening = false;
udpClient?.Close();
Console.WriteLine("Listener stopped.");
}
public static void Main(string[] args)
{
UdpReceiver receiver = new UdpReceiver();
int listenPort = 11000; // Example port
receiver.StartListening(listenPort);
Console.WriteLine("Press Enter to stop listening...");
Console.ReadLine();
receiver.StopListening();
}
}
See Also
- System.Net.Sockets.UdpClient
- System.Net.Sockets.Socket
- System.Net.IPEndPoint
- System.Net.Sockets.SocketException