System.Net.Sockets

.NET API Documentation

SocketAsyncEventArgs

Represents an object that contains data that is required to complete an asynchronous socket operation. This class is used to reduce the overhead of asynchronous socket operations by reusing the same object for multiple calls.

Inheritance

System.Object
   └── System.EventArgs
       └── System.Net.Sockets.SocketAsyncEventArgs

Namespace

System.Net.Sockets

Assembly

System.Net.Primitives.dll

Public Fields

Field Description
Completed Gets or sets the delegate that is called when the asynchronous operation completes.
SocketError Gets or sets the results of the asynchronous operation.

Public Properties

Property Description
Buffer Gets or sets the data buffer used for the asynchronous operation.
BufferList Gets or sets a list of data buffers used for the asynchronous operation.
Count Gets or sets the number of bytes to transfer or the number of bytes transferred.
Offset Gets or sets the offset in the data buffer at which to start the operation.
Port Gets or sets the port number for the asynchronous operation.
RemoteEndPoint Gets or sets the remote endpoint for the asynchronous operation.
SendBufferSize Gets or sets the size of the send buffer.
SocketFlags Gets or sets the socket flags for the asynchronous operation.
UserToken Gets or sets a user-defined object that qualifies or contains information about this asynchronous operation.

Public Methods

Method Description
AcceptAsync Starts an asynchronous operation to accept an incoming connection attempt.
ConnectAsync Starts an asynchronous operation to connect to a remote host.
DisconnectAsync Starts an asynchronous operation to disconnect the socket.
GetLookupProtocolNameAsync Starts an asynchronous operation to retrieve the protocol name for a protocol number.
GetLookupServiceByPortAsync Starts an asynchronous operation to retrieve service information for a port number.
ReceiveAsync Starts an asynchronous operation to receive data from a connected Socket.
ReceiveFromAsync Starts an asynchronous operation to receive data from a connected Socket, and stores the remote endpoint information.
ReceiveMessageFromAsync Starts an asynchronous operation to receive data from a Socket, and stores any received options and the remote endpoint information.
SendAsync Starts an asynchronous operation to send data to a connected Socket.
SendPacketsAsync Starts an asynchronous operation to send a collection of data buffers to a connected Socket.
SendToAsync Starts an asynchronous operation to send data to a Socket, using a specified remote endpoint.
SetBuffer Sets the data buffer for the operation.
SetBufferAsync Sets the data buffer for the operation.
ShutdownAsync Starts an asynchronous operation to close the Socket connection.

Method Details

Completed

public event EventHandler<SocketAsyncEventArgs> Completed;

Gets or sets the delegate that is called when the asynchronous operation completes.

This event handler is invoked by the Socket class when an asynchronous operation initiated by a method that takes a SocketAsyncEventArgs object as a parameter has finished.

SocketError

public System.Net.Sockets.SocketError SocketError;

Gets or sets the results of the asynchronous operation.

This property is set by the Socket class after the asynchronous operation has completed. It indicates the status of the operation.

Buffer

public byte[] Buffer { get; set; }

Gets or sets the data buffer used for the asynchronous operation.

For receive operations, this buffer holds the data received. For send operations, this buffer contains the data to be sent.

BufferList

public System.Collections.Generic.IList<ArraySegment<byte>> BufferList { get; set; }

Gets or sets a list of data buffers used for the asynchronous operation.

This property is useful for sending or receiving multiple contiguous buffers in a single operation, often referred to as scatter-gather I/O.

Count

public int Count { get; set; }

Gets or sets the number of bytes to transfer or the number of bytes transferred.

For send operations, this specifies the number of bytes to send from the buffer. For receive operations, this indicates the maximum number of bytes to receive.

Offset

public int Offset { get; set; }

Gets or sets the offset in the data buffer at which to start the operation.

This property is used in conjunction with the Buffer property to specify where the data resides or should be placed within the buffer.

Port

public int Port { get; set; }

Gets or sets the port number for the asynchronous operation.

This is primarily used for operations like connecting to a remote host or specifying the local port.

RemoteEndPoint

public System.Net.EndPoint RemoteEndPoint { get; set; }

Gets or sets the remote endpoint for the asynchronous operation.

This includes the IP address and port number of the remote host for connection or send-to operations, or the endpoint of the sender for receive-from operations.

SendBufferSize

public int SendBufferSize { get; set; }

Gets or sets the size of the send buffer.

This property is typically used in conjunction with SendAsync or SendPacketsAsync to indicate the desired size of the send buffer, though its direct effect can depend on the underlying operating system and socket configuration.

SocketFlags

public System.Net.Sockets.SocketFlags SocketFlags { get; set; }

Gets or sets the socket flags for the asynchronous operation.

These flags control various aspects of the socket operation, such as whether to peek at incoming data without removing it from the queue (SocketFlags.Peek) or to send data without any special options (SocketFlags.None).

UserToken

public object UserToken { get; set; }

Gets or sets a user-defined object that qualifies or contains information about this asynchronous operation.

This is a very versatile property that allows you to associate custom data with an asynchronous operation. For example, you could store a reference to a specific client object or a request context here.

Usage Example

This example demonstrates how to use SocketAsyncEventArgs to initiate an asynchronous ConnectAsync operation.


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

public class SocketClient
{
    private Socket _socket;
    private SocketAsyncEventArgs _connectArgs;

    public void ConnectToServer(string hostname, int port)
    {
        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        var remoteEndPoint = new IPEndPoint(IPAddress.Parse(hostname), port);

        _connectArgs = new SocketAsyncEventArgs();
        _connectArgs.RemoteEndPoint = remoteEndPoint;
        _connectArgs.Completed += OnConnectCompleted;

        if (!_socket.ConnectAsync(_connectArgs))
        {
            // If the operation did not complete asynchronously, handle it synchronously
            OnConnectCompleted(null, _connectArgs);
        }
    }

    private void OnConnectCompleted(object sender, SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            Console.WriteLine("Successfully connected to the server.");
            // Proceed with sending/receiving data...
        }
        else
        {
            Console.WriteLine($"Connection failed: {e.SocketError}");
        }

        // Clean up the EventArgs object if it's no longer needed
        e.Dispose();
    }

    public void Disconnect()
    {
        if (_socket != null && _socket.Connected)
        {
            var disconnectArgs = new SocketAsyncEventArgs();
            disconnectArgs.Completed += OnDisconnectCompleted;

            if (!_socket.DisconnectAsync(disconnectArgs))
            {
                OnDisconnectCompleted(null, disconnectArgs);
            }
        }
    }

    private void OnDisconnectCompleted(object sender, SocketAsyncEventArgs e)
    {
        Console.WriteLine("Disconnected.");
        e.Dispose();
        _socket.Dispose();
    }
}