Receives raw datagrams from the network and stores them in the provided buffer.
public virtual int ReceiveRawDatagrams (byte[] buffer);
| Name | Type | Description |
|---|---|---|
buffer |
System.Byte[] |
A buffer that receives a copy of the datagrams sent. The size of the buffer must be at least the size of the datagram. |
System.Int32: The number of bytes received.
The ReceiveRawDatagrams method is used to receive datagrams from a connected Socket. This method is specific to protocols that use datagrams, such as UDP. When you call this method, the Socket waits until it receives a datagram, copies the datagram into the provided buffer, and then returns the number of bytes copied.
If the datagram is larger than the buffer, the datagram is truncated to fit the buffer. The remaining data is lost. It is important to ensure that the buffer is sufficiently large to hold the expected datagrams.
| Exception Type | Condition |
|---|---|
System.ArgumentNullException |
The buffer is null. |
System.ObjectDisposedException |
The Socket has been closed. |
System.Net.Sockets.SocketException |
An error occurred when attempting to access the Socket. |
The following example demonstrates how to use the ReceiveRawDatagrams method to receive data from a UDP Socket.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpReceiver {
public static void Main(string[] args) {
const int port = 11000;
const int bufferSize = 1024;
var udpListener = new UdpClient(port);
byte[] receivedData = new byte[bufferSize];
Console.WriteLine($"Listening on port {port}...");
try {
while (true) {
// Receive data. UdpClient internally uses Socket.ReceiveFrom for UDP.
// For a direct Socket, ReceiveRawDatagrams would be used.
// This example illustrates the concept of receiving datagrams.
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
receivedData = udpListener.Receive(ref remoteEP);
string message = Encoding.ASCII.GetString(receivedData, 0, receivedData.Length);
Console.WriteLine($"Received from {remoteEP.Address}:{remoteEP.Port} - {message}");
// In a real scenario with Socket.ReceiveRawDatagrams,
// you'd manage the buffer and potentially handle partial datagrams.
}
} catch (SocketException ex) {
Console.WriteLine($"Socket error: {ex.Message}");
} finally {
udpListener.Close();
}
}
}
For non-blocking operations, consider using the asynchronous counterparts:
ReceiveAsync(SocketAsyncEventArgs): For advanced asynchronous I/O.Send(byte[])Receive(byte[]) (for stream-based protocols)ReceiveFrom(byte[], ref EndPoint) (common for UDP)