Socket class supports synchronous and asynchronous data transmission.
The Socket class is the core component for network programming in .NET. It provides low-level access to the network stack, enabling you to implement various network protocols like TCP and UDP.
It supports both connection-oriented (e.g., TCP) and connectionless (e.g., UDP) communication. The class offers methods for establishing connections, sending and receiving data, and managing network endpoints.
For higher-level abstractions, consider using classes like TcpClient, UdpClient, or the System.Net.Http namespace.
| Signature | Description |
|---|---|
| public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) | Initializes a new instance of the Socket class with the specified address family, socket type, and protocol. |
| public Socket(SocketType socketType, ProtocolType protocolType) | Initializes a new instance of the Socket class with the specified socket type and protocol. The AddressFamily is determined by the default address family for the protocol. |
| internal Socket(AddressFamily family, SocketType type, ProtocolType proto, SafeHandle irishSocket) | Internal constructor used for creating a Socket from a SafeHandle. |
| internal Socket(SocketInformation socketInformation) | Internal constructor used to create a Socket from SocketInformation. |
| Name | Type | Description |
|---|---|---|
AddressFamily |
AddressFamily |
Gets the address family for the current Socket. |
Blocking |
bool |
Gets or sets a value indicating whether the Socket is in blocking mode. |
Connected |
bool |
Gets a value indicating whether the Socket is connected to a remote host. |
DontFragment |
bool |
Gets or sets a value indicating whether the Socket uses the Don't Fragment flag. |
EnableBroadcast |
bool |
Gets or sets a value indicating whether broadcast messages are supported by this Socket. |
ExclusiveAddressUse |
bool |
Gets or sets a value indicating whether the Socket binds to a unique port. |
IOControl |
IOControlCollection |
Gets a collection of IOControl operations for the Socket. |
IsBound |
bool |
Gets a value indicating whether the Socket is bound to an endpoint. |
IsClosed |
bool |
Gets a value indicating whether the Socket has been closed. |
IsConnecting |
bool |
Gets a value indicating whether the Socket is in the process of connecting. |
LingerState |
LingerOption |
Gets or sets a LingerOption object that controls how blocking Socket operations handle remaining data when Close() is called. |
MulticastLoopback |
bool |
Gets or sets a value indicating whether multicast packets are looped back on the network interface. |
ProtocolType |
ProtocolType |
Gets the protocol type of the Socket. |
RemoteEndPoint |
EndPoint |
Gets the remote endpoint to which the Socket is connected. |
SafeHandle |
SafeHandle |
Gets the SafeHandle for the Socket. |
SendBuffer |
int |
Gets or sets the size of the buffer for sending data. |
SendTimeout |
int |
Gets or sets the time-out value for blocking send operations. |
SocketType |
SocketType |
Gets the type of the Socket. |
Ttl |
short |
Gets or sets the time-to-live value for IP packets. |
| Signature | Description |
|---|---|
| public void Accept() | Accepts an incoming connection request and creates a new Socket to handle it. |
| public IAsyncResult AcceptAsync() | Begins an asynchronous operation to accept an incoming connection request. |
| public void Bind(EndPoint localEP) | Binds the Socket to a local endpoint. |
| public IAsyncResult BindAsync(EndPoint localEP) | Begins an asynchronous operation to bind the Socket to a local endpoint. |
| public void Close() | Releases all resources used by the Socket. |
| public void Connect(EndPoint remoteEP) | Establishes a connection to a remote host. |
| public IAsyncResult ConnectAsync(EndPoint remoteEP) | Begins an asynchronous operation to establish a connection to a remote host. |
| public int Receive(byte[] buffer) | Receives data from the connected Socket into the specified buffer. |
| public int Receive(byte[] buffer, SocketFlags socketFlags) | Receives data from the connected Socket into the specified buffer and with the specified SocketFlags. |
| public int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP) | Receives data from the Socket and stores the data in the specified buffer and the endpoint of the datagram in the EndPoint. |
| public IAsyncResult ReceiveAsync(ArraySegment<byte> buffer, SocketFlags socketFlags) | Begins an asynchronous operation to receive data from the Socket. |
| public int Send(byte[] buffer) | Sends data from the specified buffer to the connected Socket. |
| public int Send(byte[] buffer, SocketFlags socketFlags) | Sends data from the specified buffer to the connected Socket and with the specified SocketFlags. |
| public int SendTo(byte[] buffer, EndPoint remoteEP) | Sends data to a specific remote host. |
| public IAsyncResult SendAsync(ArraySegment<byte> buffer, SocketFlags socketFlags) | Begins an asynchronous operation to send data to the Socket. |
The Socket class does not expose public events.
The Socket class does not expose public fields.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TcpClientExample
{
public static void Main(string[] args)
{
// Define server IP address and port
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
int port = 11000;
using (Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
try
{
// Connect to the server
IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, port);
clientSocket.Connect(remoteEndPoint);
Console.WriteLine("Connected to server.");
// Send a message
string message = "Hello from the client!";
byte[] messageBytes = Encoding.ASCII.GetBytes(message);
clientSocket.Send(messageBytes, 0, messageBytes.Length, SocketFlags.None);
Console.WriteLine("Message sent: " + message);
// Receive a response
byte[] buffer = new byte[1024];
int bytesReceived = clientSocket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
string response = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
Console.WriteLine("Response received: " + response);
}
catch (SocketException ex)
{
Console.WriteLine("SocketException: {0}", ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
}
}
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpServerExample
{
public static void Main(string[] args)
{
int port = 11000;
byte[] buffer = new byte[1024];
using (Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
try
{
// Bind the socket to the local endpoint
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
serverSocket.Bind(localEndPoint);
Console.WriteLine("UDP Server started on port {0}.", port);
// Listen for incoming datagrams
EndPoint remoteEndPoint = new IPEndPoint(0, 0); // Used to store the client's endpoint
while (true)
{
int bytesReceived = serverSocket.ReceiveFrom(buffer, ref remoteEndPoint);
string message = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
Console.WriteLine("Received from {0}: {1}", remoteEndPoint.ToString(), message);
// Send a response back to the client
string response = "Message received by server!";
byte[] responseBytes = Encoding.ASCII.GetBytes(response);
serverSocket.SendTo(responseBytes, remoteEndPoint);
Console.WriteLine("Sent response to {0}", remoteEndPoint.ToString());
}
}
catch (SocketException ex)
{
Console.WriteLine("SocketException: {0}", ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex.Message);
}
}
}
}