5 out of 14 rated this helpful - Rate this topic

Socket Class

Implements the Berkeley sockets interface.

System.Object
  System.Net.Sockets.Socket

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)
public class Socket : IDisposable

The Socket type exposes the following members.

  Name Description
Public method Socket(SocketInformation) Initializes a new instance of the Socket class using the specified value returned from DuplicateAndClose.
Public method Socket(AddressFamily, SocketType, ProtocolType) Initializes a new instance of the Socket class using the specified address family, socket type and protocol.
Top
  Name Description
Public property AddressFamily Gets the address family of the Socket.
Public property Available Gets the amount of data that has been received from the network and is available to be read.
Public property Blocking Gets or sets a value that indicates whether the Socket is in blocking mode.
Public property Connected Gets a value that indicates whether a Socket is connected to a remote host as of the last Send or Receive operation.
Public property DontFragment Gets or sets a Boolean value that specifies whether the Socket allows Internet Protocol (IP) datagrams to be fragmented.
Public property EnableBroadcast Gets or sets a Boolean value that specifies whether the Socket can send or receive broadcast packets.
Public property ExclusiveAddressUse Gets or sets a Boolean value that specifies whether the Socket allows only one process to bind to a port.
Public property Handle Gets the operating system handle for the Socket.
Public property IsBound Gets a value that indicates whether the Socket is bound to a specific local port.
Public property LingerState Gets or sets a value that specifies whether the Socket will delay closing a socket in an attempt to send all pending data.
Public property LocalEndPoint Gets the local endpoint.
Public property MulticastLoopback Gets or sets a value that specifies whether outgoing multicast packets are delivered to the sending application.
Public property NoDelay Gets or sets a Boolean value that specifies whether the stream Socket is using the Nagle algorithm.
Public property Static member OSSupportsIPv4 Indicates whether the underlying operating system and network adaptors support Internet Protocol version 4 (IPv4).
Public property Static member OSSupportsIPv6 Indicates whether the underlying operating system and network adaptors support Internet Protocol version 6 (IPv6).
Public property ProtocolType Gets the protocol type of the Socket.
Public property ReceiveBufferSize Gets or sets a value that specifies the size of the receive buffer of the Socket.
Public property ReceiveTimeout Gets or sets a value that specifies the amount of time after which a synchronous Receive call will time out.
Public property RemoteEndPoint Gets the remote endpoint.
Public property SendBufferSize Gets or sets a value that specifies the size of the send buffer of the Socket.
Public property SendTimeout Gets or sets a value that specifies the amount of time after which a synchronous Send call will time out.
Public property SocketType Gets the type of the Socket.
Public property Static member SupportsIPv4 Obsolete. Gets a value indicating whether IPv4 support is available and enabled on the current host.
Public property Static member SupportsIPv6 Obsolete. Gets a value that indicates whether the Framework supports IPv6 for certain obsolete Dns members.
Public property Ttl Gets or sets a value that specifies the Time To Live (TTL) value of Internet Protocol (IP) packets sent by the Socket.
Public property UseOnlyOverlappedIO Specifies whether the socket should only use Overlapped I/O mode.
Top
  Name Description
Public method Accept Creates a new Socket for a newly created connection.
Public method AcceptAsync Begins an asynchronous operation to accept an incoming connection attempt.
Public method BeginAccept(AsyncCallback, Object) Begins an asynchronous operation to accept an incoming connection attempt.
Public method BeginAccept(Int32, AsyncCallback, Object) Begins an asynchronous operation to accept an incoming connection attempt and receives the first block of data sent by the client application.
Public method BeginAccept(Socket, Int32, AsyncCallback, Object) Begins an asynchronous operation to accept an incoming connection attempt from a specified socket and receives the first block of data sent by the client application.
Public method BeginConnect(EndPoint, AsyncCallback, Object) Begins an asynchronous request for a remote host connection.
Public method BeginConnect(IPAddress, Int32, AsyncCallback, Object) Begins an asynchronous request for a remote host connection. The host is specified by an IPAddress and a port number.
Public method BeginConnect(IPAddress[], Int32, AsyncCallback, Object) Begins an asynchronous request for a remote host connection. The host is specified by an IPAddress array and a port number.
Public method BeginConnect(String, Int32, AsyncCallback, Object) Begins an asynchronous request for a remote host connection. The host is specified by a host name and a port number.
Public method BeginDisconnect Begins an asynchronous request to disconnect from a remote endpoint.
Public method BeginReceive(IList<ArraySegment<Byte>>, SocketFlags, AsyncCallback, Object) Begins to asynchronously receive data from a connected Socket.
Public method BeginReceive(IList<ArraySegment<Byte>>, SocketFlags, SocketError, AsyncCallback, Object) Begins to asynchronously receive data from a connected Socket.
Public method BeginReceive(Byte[], Int32, Int32, SocketFlags, AsyncCallback, Object) Begins to asynchronously receive data from a connected Socket.
Public method BeginReceive(Byte[], Int32, Int32, SocketFlags, SocketError, AsyncCallback, Object) Begins to asynchronously receive data from a connected Socket.
Public method BeginReceiveFrom Begins to asynchronously receive data from a specified network device.
Public method BeginReceiveMessageFrom Begins to asynchronously receive the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint and packet information..
Public method BeginSend(IList<ArraySegment<Byte>>, SocketFlags, AsyncCallback, Object) Sends data asynchronously to a connected Socket.
Public method BeginSend(IList<ArraySegment<Byte>>, SocketFlags, SocketError, AsyncCallback, Object) Sends data asynchronously to a connected Socket.
Public method BeginSend(Byte[], Int32, Int32, SocketFlags, AsyncCallback, Object) Sends data asynchronously to a connected Socket.
Public method BeginSend(Byte[], Int32, Int32, SocketFlags, SocketError, AsyncCallback, Object) Sends data asynchronously to a connected Socket.
Public method BeginSendFile(String, AsyncCallback, Object) Sends the file fileName to a connected Socket object using the UseDefaultWorkerThread flag.
Public method BeginSendFile(String, Byte[], Byte[], TransmitFileOptions, AsyncCallback, Object) Sends a file and buffers of data asynchronously to a connected Socket object.
Public method BeginSendTo Sends data asynchronously to a specific remote host.
Public method Bind Associates a Socket with a local endpoint.
Public method Static member CancelConnectAsync Cancels an asynchronous request for a remote host connection.
Public method Close() Closes the Socket connection and releases all associated resources.
Public method Close(Int32) Closes the Socket connection and releases all associated resources with a specified timeout to allow queued data to be sent.
Public method Connect(EndPoint) Establishes a connection to a remote host.
Public method Connect(IPAddress, Int32) Establishes a connection to a remote host. The host is specified by an IP address and a port number.
Public method Connect(IPAddress[], Int32) Establishes a connection to a remote host. The host is specified by an array of IP addresses and a port number.
Public method Connect(String, Int32) Establishes a connection to a remote host. The host is specified by a host name and a port number.
Public method ConnectAsync(SocketAsyncEventArgs) Begins an asynchronous request for a remote host connection.
Public method Static member ConnectAsync(SocketType, ProtocolType, SocketAsyncEventArgs) Begins an asynchronous request for a remote host connection.
Public method Disconnect Closes the socket connection and allows reuse of the socket.
Public method DisconnectAsync Begins an asynchronous request to disconnect from a remote endpoint.
Public method Dispose() Releases all resources used by the current instance of the Socket class.
Protected method Dispose(Boolean) Releases the unmanaged resources used by the Socket, and optionally disposes of the managed resources.
Public method DuplicateAndClose Duplicates the socket reference for the target process, and closes the socket for this process.
Public method EndAccept(IAsyncResult) Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.
Public method EndAccept(Byte[], IAsyncResult) Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. This method returns a buffer that contains the initial data transferred.
Public method EndAccept(Byte[], Int32, IAsyncResult) Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. This method returns a buffer that contains the initial data and the number of bytes transferred.
Public method EndConnect Ends a pending asynchronous connection request.
Public method EndDisconnect Ends a pending asynchronous disconnect request.
Public method EndReceive(IAsyncResult) Ends a pending asynchronous read.
Public method EndReceive(IAsyncResult, SocketError) Ends a pending asynchronous read.
Public method EndReceiveFrom Ends a pending asynchronous read from a specific endpoint.
Public method EndReceiveMessageFrom Ends a pending asynchronous read from a specific endpoint. This method also reveals more information about the packet than EndReceiveFrom.
Public method EndSend(IAsyncResult) Ends a pending asynchronous send.
Public method EndSend(IAsyncResult, SocketError) Ends a pending asynchronous send.
Public method EndSendFile Ends a pending asynchronous send of a file.
Public method EndSendTo Ends a pending asynchronous send to a specific location.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Frees resources used by the Socket class. (Overrides Object.Finalize().)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetSocketOption(SocketOptionLevel, SocketOptionName) Returns the value of a specified Socket option, represented as an object.
Public method GetSocketOption(SocketOptionLevel, SocketOptionName, Byte[]) Returns the specified Socket option setting, represented as a byte array.
Public method GetSocketOption(SocketOptionLevel, SocketOptionName, Int32) Returns the value of the specified Socket option in an array.
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method IOControl(Int32, Byte[], Byte[]) Sets low-level operating modes for the Socket using numerical control codes.
Public method IOControl(IOControlCode, Byte[], Byte[]) Sets low-level operating modes for the Socket using the IOControlCode enumeration to specify control codes.
Public method Listen Places a Socket in a listening state.
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Public method Poll Determines the status of the Socket.
Public method Receive(IList<ArraySegment<Byte>>) Receives data from a bound Socket into the list of receive buffers.
Public method Receive(Byte[]) Receives data from a bound Socket into a receive buffer.
Public method Receive(IList<ArraySegment<Byte>>, SocketFlags) Receives data from a bound Socket into the list of receive buffers, using the specified SocketFlags.
Public method Receive(Byte[], SocketFlags) Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.
Public method Receive(IList<ArraySegment<Byte>>, SocketFlags, SocketError) Receives data from a bound Socket into the list of receive buffers, using the specified SocketFlags.
Public method Receive(Byte[], Int32, SocketFlags) Receives the specified number of bytes of data from a bound Socket into a receive buffer, using the specified SocketFlags.
Public method Receive(Byte[], Int32, Int32, SocketFlags) Receives the specified number of bytes from a bound Socket into the specified offset position of the receive buffer, using the specified SocketFlags.
Public method Receive(Byte[], Int32, Int32, SocketFlags, SocketError) Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.
Public method ReceiveAsync Begins an asynchronous request to receive data from a connected Socket object.
Public method ReceiveFrom(Byte[], EndPoint) Receives a datagram into the data buffer and stores the endpoint.
Public method ReceiveFrom(Byte[], SocketFlags, EndPoint) Receives a datagram into the data buffer, using the specified SocketFlags, and stores the endpoint.
Public method ReceiveFrom(Byte[], Int32, SocketFlags, EndPoint) Receives the specified number of bytes into the data buffer, using the specified SocketFlags, and stores the endpoint.
Public method ReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint) Receives the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint.
Public method ReceiveFromAsync Begins to asynchronously receive data from a specified network device.
Public method ReceiveMessageFrom Receives the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint and packet information.
Public method ReceiveMessageFromAsync Begins to asynchronously receive the specified number of bytes of data into the specified location in the data buffer, using the specified SocketAsyncEventArgs.SocketFlags, and stores the endpoint and packet information.
Public method Static member Select Determines the status of one or more sockets.
Public method Send(IList<ArraySegment<Byte>>) Sends the set of buffers in the list to a connected Socket.
Public method Send(Byte[]) Sends data to a connected Socket.
Public method Send(IList<ArraySegment<Byte>>, SocketFlags) Sends the set of buffers in the list to a connected Socket, using the specified SocketFlags.
Public method Send(Byte[], SocketFlags) Sends data to a connected Socket using the specified SocketFlags.
Public method Send(IList<ArraySegment<Byte>>, SocketFlags, SocketError) Sends the set of buffers in the list to a connected Socket, using the specified SocketFlags.
Public method Send(Byte[], Int32, SocketFlags) Sends the specified number of bytes of data to a connected Socket, using the specified SocketFlags.
Public method Send(Byte[], Int32, Int32, SocketFlags) Sends the specified number of bytes of data to a connected Socket, starting at the specified offset, and using the specified SocketFlags.
Public method Send(Byte[], Int32, Int32, SocketFlags, SocketError) Sends the specified number of bytes of data to a connected Socket, starting at the specified offset, and using the specified SocketFlags
Public method SendAsync Sends data asynchronously to a connected Socket object.
Public method SendFile(String) Sends the file fileName to a connected Socket object with the UseDefaultWorkerThread transmit flag.
Public method SendFile(String, Byte[], Byte[], TransmitFileOptions) Sends the file fileName and buffers of data to a connected Socket object using the specified TransmitFileOptions value.
Public method SendPacketsAsync Sends a collection of files or in memory data buffers asynchronously to a connected Socket object.
Public method SendTo(Byte[], EndPoint) Sends data to the specified endpoint.
Public method SendTo(Byte[], SocketFlags, EndPoint) Sends data to a specific endpoint using the specified SocketFlags.
Public method SendTo(Byte[], Int32, SocketFlags, EndPoint) Sends the specified number of bytes of data to the specified endpoint using the specified SocketFlags.
Public method SendTo(Byte[], Int32, Int32, SocketFlags, EndPoint) Sends the specified number of bytes of data to the specified endpoint, starting at the specified location in the buffer, and using the specified SocketFlags.
Public method SendToAsync Sends data asynchronously to a specific remote host.
Public method SetIPProtectionLevel Set the IP protection level on a socket.
Public method SetSocketOption(SocketOptionLevel, SocketOptionName, Boolean) Sets the specified Socket option to the specified Boolean value.
Public method SetSocketOption(SocketOptionLevel, SocketOptionName, Byte[]) Sets the specified Socket option to the specified value, represented as a byte array.
Public method SetSocketOption(SocketOptionLevel, SocketOptionName, Int32) Sets the specified Socket option to the specified integer value.
Public method SetSocketOption(SocketOptionLevel, SocketOptionName, Object) Sets the specified Socket option to the specified value, represented as an object.
Public method Shutdown Disables sends and receives on a Socket.
Public method ToString Returns a string that represents the current object. (Inherited from Object.)
Top

The Socket class provides a rich set of methods and properties for network communications. The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration.

The Socket class follows the .NET Framework naming pattern for asynchronous methods. For example, the synchronous Receive method corresponds to the asynchronous BeginReceive and EndReceive methods.

If your application only requires one thread during execution, use the following methods, which are designed for synchronous operation mode.

  • If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the Listen method. The Accept method processes any incoming connection requests and returns a Socket that you can use to communicate data with the remote host. Use this returned Socket to call the Send or Receive method. Call the Bind method prior to calling the Listen method if you want to specify the local IP address and port number. Use a port number of zero if you want the underlying service provider to assign a free port for you. If you want to connect to a listening host, call the Connect method. To communicate data, call the Send or Receive method.

  • If you are using a connectionless protocol such as UDP, you do not need to listen for connections at all. Call the ReceiveFrom method to accept any incoming datagrams. Use the SendTo method to send datagrams to a remote host.

To process communications using separate threads during execution, use the following methods, which are designed for asynchronous operation mode.

If you perform multiple asynchronous operations on a socket, they do not necessarily complete in the order in which they are started.

When you are finished sending and receiving data, use the Shutdown method to disable the Socket. After calling Shutdown, call the Close method to release all resources associated with the Socket.

The Socket class allows you to configure your Socket using the SetSocketOption method. Retrieve these settings using the GetSocketOption method.

Note Note

If you are writing a relatively simple application and do not require maximum performance, consider using TcpClient, TcpListener, and UdpClient. These classes provide a simpler and more user-friendly interface to Socket communications.

The following code example shows how the Socket class can be used to send data to an HTTP server and receive the response. This example blocks until the entire page is received.


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

public class GetSocket
{
    private static Socket ConnectSocket(string server, int port)
    {
        Socket s = null;
        IPHostEntry hostEntry = null;

        // Get host related information.
        hostEntry = Dns.GetHostEntry(server);

        // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
        // an exception that occurs when the host IP Address is not compatible with the address family
        // (typical in the IPv6 case).
        foreach(IPAddress address in hostEntry.AddressList)
        {
            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket tempSocket = 
                new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            tempSocket.Connect(ipe);

            if(tempSocket.Connected)
            {
                s = tempSocket;
                break;
            }
            else
            {
                continue;
            }
        }
        return s;
    }

    // This method requests the home page content for the specified server.
    private static string SocketSendReceive(string server, int port) 
    {
        string request = "GET / HTTP/1.1\r\nHost: " + server + 
            "\r\nConnection: Close\r\n\r\n";
        Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
        Byte[] bytesReceived = new Byte[256];

        // Create a socket connection with the specified server and port.
        Socket s = ConnectSocket(server, port);

        if (s == null)
            return ("Connection failed");

        // Send request to the server.
        s.Send(bytesSent, bytesSent.Length, 0);  

        // Receive the server home page content.
        int bytes = 0;
        string page = "Default HTML page on " + server + ":\r\n";

        // The following will block until te page is transmitted.
        do {
            bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
            page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
        }
        while (bytes > 0);

        return page;
    }

    public static void Main(string[] args) 
    {
        string host;
        int port = 80;

        if (args.Length == 0)
            // If no server name is passed as argument to this program, 
            // use the current host name as the default.
            host = Dns.GetHostName();
        else
            host = args[0];

        string result = SocketSendReceive(host, port); 
        Console.WriteLine(result);
    }
}



.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
  • SocketPermission  

    To establish an outgoing connection or accept an incoming request.

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Instances of this class are thread safe.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Winsock reference
A good resource for .NET developers that are less familiar with socket programming is the Windows Sockets 2 area on msdn.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms740673(v=vs.85).aspx

The Winsock reference provides a lot more detail than the documentation for these .NET abstractions. I found it particularly useful when writing socket error handling.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms741416(v=vs.85).aspx
.Net Protocol Builder for TCP Protocols
Socket class gives too much complexity here, I used .Net Protocol Builder for TCP protocols ( http://www.protocol-builder.com ) to generate the C# code for me, that's much easier and faster, actually I could waste one month for coding and debugging the protocol !!