| Name | Description |
|---|---|
| SocketBuilder() | Initializes a new instance of the SocketBuilder class with default settings (e.g., IPv4, Stream, TCP). |
| Name | Description |
|---|---|
| WithAddressFamily(AddressFamily addressFamily) | Configures the SocketBuilder to use the specified address family. |
| WithSocketType(SocketType socketType) | Configures the SocketBuilder to use the specified socket type. |
| WithProtocolType(ProtocolType protocolType) | Configures the SocketBuilder to use the specified protocol type. |
| WithOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue) | Enables a specific socket option with an integer value. |
| WithOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue) | Enables a specific socket option with a boolean value. |
| WithLingerOption(int lingerTime, int lingerOn) | Configures the linger option for the socket. |
| WithExclusiveAddressUse(bool useExclusiveAddress) | Sets whether to use exclusive address binding. |
| Build() | Creates and returns a new Socket instance with the configured options. |
The SocketBuilder class follows the Builder pattern, allowing for a more readable and maintainable way to construct complex Socket objects. Each configuration method returns the SocketBuilder instance itself, enabling method chaining.
This class is particularly useful when you need to create sockets with non-default settings, such as binding to a specific IP version (IPv4/IPv6), using different socket types (Stream, Dgram), or enabling advanced socket options like SO_REUSEADDR or TCP_NODELAY.
using System;
using System.Net;
using System.Net.Sockets;
public class SocketExample
{
public static void Main()
{
// Create a TCP/IP socket for IPv4, enabling address reuse
using (Socket socket = new SocketBuilder()
.WithAddressFamily(AddressFamily.InterNetwork)
.WithSocketType(SocketType.Stream)
.WithProtocolType(ProtocolType.Tcp)
.WithOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true)
.Build())
{
// Now you can use the 'socket' object for communication
Console.WriteLine($"Socket created with: {socket.AddressFamily}, {socket.SocketType}, {socket.ProtocolType}");
// Example: Bind the socket
// socket.Bind(new IPEndPoint(IPAddress.Any, 12345));
// Example: Listen for connections
// socket.Listen(10);
}
// Create a UDP socket for IPv6
using (Socket udpSocket = new SocketBuilder()
.WithAddressFamily(AddressFamily.InterNetworkV6)
.WithSocketType(SocketType.Dgram)
.WithProtocolType(ProtocolType.Udp)
.Build())
{
Console.WriteLine($"UDP Socket created with: {udpSocket.AddressFamily}, {udpSocket.SocketType}");
}
}
}