.NET API Reference
.NET Library > System.Net.Sockets > Socket.Receive

Socket.Receive Method

Receives data from a connected Socket into a receive buffer.

public int Receive(byte[] buffer);

Syntax

public int Receive(byte[] buffer);

Parameters

buffer: byte[]
A byte array that receives data from the network. This parameter cannot be null.

Returns

int
The number of bytes received. This will be zero if the connection is closed and all bytes have been received.

Exceptions

ArgumentNullException:
The buffer parameter is null.
SocketException:
An error occurred when attempting to access the socket.
ObjectDisposedException:
The Socket has been closed.

Remarks

The Receive method reads up to buffer.Length bytes from the socket into the buffer. If no data is available, the Receive method will block until data is available. If the remote host shuts down the Socket connection, and all available data has been received, the Receive method will complete immediately and return zero bytes. If you are using a connection-oriented stream, you may need to call Receive more than once to receive all of the data. You can determine how many bytes are available to be read without blocking by using the Available property.

Examples

The following code example demonstrates how to use the Receive method.


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

public class Example
{
    public static void ReceiveData(Socket socket)
    {
        try
        {
            byte[] buffer = new byte[1024];
            int bytesReceived = socket.Receive(buffer);

            if (bytesReceived > 0)
            {
                string receivedString = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
                Console.WriteLine($"Received: {receivedString}");
            }
            else
            {
                Console.WriteLine("Connection closed by remote host.");
            }
        }
        catch (SocketException ex)
        {
            Console.WriteLine($"SocketException: {ex.Message}");
        }
        catch (ObjectDisposedException)
        {
            Console.WriteLine("Socket has been disposed.");
        }
    }

    // Example usage (simplified, assumes socket is connected)
    public static void Main(string[] args)
    {
        // This is a placeholder for demonstration.
        // In a real application, you would create and connect the socket.
        // For instance:
        // Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        // listener.Bind(new IPEndPoint(IPAddress.Any, 1111));
        // listener.Listen(10);
        // Socket handler = listener.Accept();
        // ReceiveData(handler);
        // handler.Close();
        // listener.Close();

        Console.WriteLine("Example usage requires a connected socket. This is a conceptual demonstration.");
    }
}
        

Requirements

Namespace: System.Net.Sockets

Assembly: System.Net.Sockets.dll