SocketBindingElement
Namespace: System.Net.Sockets
Class
Represents a configuration element for binding a socket.
Constructors
public SocketBindingElement()
Initializes a new instance of the SocketBindingElement class.
public SocketBindingElement(string name)
Initializes a new instance of the SocketBindingElement class with the specified name.
Parameters
stringname: The name of the binding element.
Properties
public string Name { get; set; }
Gets or sets the name of the binding element.
public int Port { get; set; }
Gets or sets the port number for the socket binding.
public string Address { get; set; }
Gets or sets the IP address for the socket binding.
Methods
public void Bind(Socket socket)
Binds the specified socket to the configured address and port.
Parameters
Socketsocket: The socket to bind.
public void Unbind(Socket socket)
Unbinds the specified socket from its configured address and port.
Parameters
Socketsocket: The socket to unbind.
public static SocketBindingElement Parse(string configuration)
Parses a configuration string and returns a new instance of the SocketBindingElement class.
Parameters
stringconfiguration: The configuration string to parse.
Returns
- A new
SocketBindingElementinstance based on the configuration string.
Example Usage
using System;
using System.Net.Sockets;
public class Example
{
public static void Main(string[] args)
{
// Create a new socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Define a binding element
SocketBindingElement binding = new SocketBindingElement();
binding.Name = "MyServerBinding";
binding.Address = "127.0.0.1";
binding.Port = 8080;
try
{
// Bind the socket
binding.Bind(socket);
Console.WriteLine($"Socket bound to {binding.Address}:{binding.Port}");
// ... perform socket operations ...
}
catch (SocketException ex)
{
Console.WriteLine($"Socket error: {ex.Message}");
}
finally
{
// Unbind the socket
if (socket.IsBound)
{
binding.Unbind(socket);
Console.WriteLine("Socket unbound.");
}
socket.Close();
}
}
}