Socket Class
Represents a socket, which is an endpoint for sending and receiving data across a network. This class provides a managed wrapper around the underlying operating system's socket implementation.
Introduction
The Socket class is the fundamental class for network communication in the .NET Framework. It allows applications to create and manage network connections using various protocols such as TCP and UDP.
When using Socket, you typically need to consider the following aspects:
- Creating a
Socketinstance with a specific address family (e.g., IPv4, IPv6), socket type (e.g., Stream, Dgram), and protocol. - Binding the socket to a local endpoint.
- Listening for incoming connections (for connection-oriented protocols like TCP).
- Accepting connections from clients.
- Connecting to a remote host.
- Sending and receiving data.
- Closing the socket to release resources.
Constructors
Public Constructors
-
Socket(AddressFamily, SocketType, ProtocolType)
Initializes a new instance of the
Socketclass with the specified address family, socket type, and protocol. -
Socket(SocketInformation)
Initializes a new instance of the
Socketclass from the specifiedSocketInformationobject.
Properties
| Name | Type | Description |
|---|---|---|
| AddressFamily | AddressFamily |
Gets the address family of the current Socket. |
| Blocking | Boolean |
Gets or sets a value that indicates whether the Socket is in blocking mode. |
| Connected | Boolean |
Gets a value that indicates whether the Socket is connected to a remote host. |
| DontFragment | Boolean |
Gets or sets a value that indicates whether the Socket allows data to be fragmented. |
| DontLinger | Boolean |
Gets or sets a value that indicates whether a Socket lingers when it is closed. |
| EnableBroadcast | Boolean |
Gets or sets a value that indicates whether broadcast packets can be sent using the Socket. |
| Handle | IntPtr |
Gets the native handle of the Socket. |
| IsBound | Boolean |
Gets a value that indicates whether the Socket is bound to an endpoint. |
| LingerState | LingerOption |
Gets or sets a LingerOption object that specifies whether and how long a Socket lingers when data is sent. |
| MulticastLoopback | Boolean |
Gets or sets a value that indicates whether multicast packets can be received on the Socket when the same Socket is sending. |
| ProtocolType | ProtocolType |
Gets the protocol type of the current Socket. |
| ReceiveBufferSize | Int32 |
Gets or sets the size of the buffer for incoming data. |
| ReceiveTimeout | Int32 |
Gets or sets the amount of time, in milliseconds, that a Socket will attempt to receive data before timing out. |
| SendBufferSize | Int32 |
Gets or sets the size of the buffer for outgoing data. |
| SendTimeout | Int32 |
Gets or sets the amount of time, in milliseconds, that a Socket will attempt to send data before timing out. |
| SocketType | SocketType |
Gets the socket type of the current Socket. |
Methods
| Name | Description |
|---|---|
| Accept() | Accepts an incoming connection attempt and creates a new Socket to handle remote host communication. |
| Bind(EndPoint) | Binds a Socket to an endpoint. |
| Close() | Releases the resources used by the Socket. |
| Connect(EndPoint) | Establishes a connection to a remote host. |
| GetSocketOption(SocketOptionLevel, SocketOptionName) | Gets a Socket option. |
| Listen(Int32) | Starts listening for incoming connection attempts. |
| Poll(Int32, SelectMode) | Determines the status of the specified Socket against the specified event. |
| Receive(Byte[]) | Receives data from the connected Socket into a buffer. |
| ReceiveFrom(Byte[], EndPoint) | Receives data from a connected Socket into a buffer, using the EndPoint to specify the remote host. |
| Send(Byte[]) | Sends the entire buffer of data to the connected Socket. |
| SendTo(Byte[], EndPoint) | Sends data to a connected Socket, using the EndPoint to specify the remote host. |
| SetSocketOption(SocketOptionLevel, SocketOptionName, Int32) | Sets a Socket option. |
| Shutdown(SocketShutdown) | Disables sends, receives, or both on the Socket. |
Events
The Socket class does not expose public events directly. Asynchronous operations often use callbacks or Task-based asynchronous patterns.
Remarks
The Socket class offers both synchronous and asynchronous methods for network operations. Synchronous methods block the calling thread until the operation completes, while asynchronous methods return immediately and allow the operation to continue in the background.
For connection-oriented protocols like TCP (e.g., SocketType.Stream), you typically follow these steps:
- Create a
Socket. Bindit to a local endpoint.Listenfor incoming connections.Accepta connection, which returns a newSocketfor that specific connection.- Use the new
SockettoSendandReceivedata. Closethe socket when done.
For connectionless protocols like UDP (e.g., SocketType.Dgram), the process is simpler:
- Create a
Socket. - Optionally
Bindit to a local endpoint. - Use
SendToto send data to a specific remote endpoint andReceiveFromto receive data from any endpoint. Closethe socket when done.
It is crucial to manage the lifecycle of a Socket properly by calling Close or disposing of it to release unmanaged resources and prevent network port leaks. Using a using statement in C# is highly recommended for this.
Exceptions
The Socket class can throw various exceptions, including but not limited to:
ArgumentNullException: If a null argument is passed to a method.ArgumentOutOfRangeException: If an argument is outside the valid range.SocketException: For a wide range of network-related errors.ObjectDisposedException: If an operation is performed on a disposedSocket.SocketException: Indicates a network-related error occurred.
Examples
TCP Server Example (Simplified)
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TcpServer
{
public static void StartServer(int port)
{
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
try
{
listener.Bind(localEndPoint);
listener.Listen(10); // Max backlog of 10 connections
Console.WriteLine($"Listening on port {port}...");
while (true)
{
Socket handler = listener.Accept(); // Blocks until a client connects
Console.WriteLine($"Client connected: {handler.RemoteEndPoint}");
// Handle client communication (simplified)
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
string data = Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine($"Received: {data}");
byte[] msg = Encoding.ASCII.GetBytes("Hello from server!");
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
listener.Close();
}
}
// To run this example, call TcpServer.StartServer(11000); in your application.
}
UDP Client Example (Simplified)
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpClient
{
public static void SendMessage(string ipAddress, int port, string message)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
byte[] messageBytes = Encoding.ASCII.GetBytes(message);
try
{
socket.SendTo(messageBytes, remoteEndPoint);
Console.WriteLine($"Sent '{message}' to {ipAddress}:{port}");
// Optionally receive a response
byte[] buffer = new byte[1024];
EndPoint remote = new IPEndPoint(IPAddress.Any, 0);
int bytesRead = socket.ReceiveFrom(buffer, ref remote);
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received from {remote}: {response}");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
socket.Close();
}
}
// To run this example, call UdpClient.SendMessage("127.0.0.1", 11001, "Hello UDP!"); in your application.
}