Socket Class

Provides the Windows Sockets API for network access.
Namespace: System.Net.Sockets
Assembly: System (in System.dll)

Syntax

public class Socket : IDisposable

Remarks

The Socket class provides access to the low-level Windows Sockets API. You can use the Socket class to create a socket and then bind, listen, accept, connect, send, and receive data.

To use the Socket class, you must first create a new instance of the Socket class. When you create a Socket, you must specify the address family (for example, AddressFamily.InterNetwork for IPv4 or AddressFamily.InterNetworkV6 for IPv6), the socket type (for example, SocketType.Stream for a reliable, connection-oriented socket or SocketType.Dgram for a connectionless socket), and the protocol type (for example, ProtocolType.Tcp or ProtocolType.Udp).

After you create a Socket, you can:

The Socket class supports both synchronous and asynchronous operations. Asynchronous operations allow your application to continue executing while the socket operation is in progress, which can improve performance and responsiveness.

Constructors

Socket(SocketType, ProtocolType)

public Socket(SocketType socketType, ProtocolType protocolType)

Initializes a new instance of the Socket class using the specified socket type and protocol type.

socketType
A SocketType value that specifies the type of socket to create.
protocolType
A ProtocolType value that specifies the protocol to use.

Socket(AddressFamily, SocketType, ProtocolType)

public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)

Initializes a new instance of the Socket class using the specified address family, socket type, and protocol type.

addressFamily
An AddressFamily value that specifies the address family of the socket.
socketType
A SocketType value that specifies the type of socket to create.
protocolType
A ProtocolType value that specifies the protocol to use.

Methods

Bind(EndPoint)

public void Bind(EndPoint localEP)

Binds a Socket to a local endpoint.

localEP
An EndPoint that represents the local endpoint to which to bind the socket.

Connect(EndPoint)

public void Connect(EndPoint remoteEP)

Establishes a connection to a remote host. (For connection-oriented sockets.)

remoteEP
An EndPoint that represents the remote device to which to connect.

Accept()

public Socket Accept()

Accepts a pending connection request and creates a new Socket to handle the remote device.

Send(byte[])

public int Send(byte[] buffer)

Sends the entire buffer buffer to the connected Socket.

buffer
A byte[] array containing the data to send.
Note: This is a synchronous method. For asynchronous sending, consider using SendAsync.

Receive(byte[])

public int Receive(byte[] buffer)

Receives data from the connected Socket and stores it in the specified buffer.

buffer
A byte[] array to store the received data.
Note: This is a synchronous method. For asynchronous receiving, consider using ReceiveAsync.

Close()

public void Close()

Closes the Socket connection.

Example

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

public class SimpleTcpClient
{
    public static void Main(string[] args)
    {
        try
        {
            // Define the remote endpoint for the socket.
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            int port = 11000;
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a TCP/IP socket.
            using (Socket sender = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp))
            {
                // Connect to the remote endpoint.
                sender.Connect(remoteEP);

                Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());

                // Encode the data string into a byte array.
                string message = "This is a test message.";
                byte[] msg = Encoding.UTF8.GetBytes(message + "");

                // Send the data through the socket.
                int bytesSent = sender.Send(msg);
                Console.WriteLine("Sent {0} bytes to server.", bytesSent);

                // Receive the response from the client.
                byte[] bytes = new byte[1024];
                int bytesRec = sender.Receive(bytes);
                Console.WriteLine("Received {0} bytes from server: {1}",
                    bytesRec, Encoding.UTF8.GetString(bytes, 0, bytesRec));

                // Release the socket.
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();
            }
        }
        catch (ArgumentNullException ane)
        {
            Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
        }
        catch (SocketException se)
        {
            Console.WriteLine("SocketException : {0}", se.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine("Unexpected exception : {0}", e.ToString());
        }
    }
}

Inheritance Hierarchy

Object
   System.MarshalByRefObject
     System.Net.Sockets.Socket

Implements

System.IDisposable

Back to Top