Socket Class
Summary
Provides the managed implementation of the Windows Sockets API.
The Socket
class provides access to the low-level networking functionality that is exposed by the Windows Sockets API. This class is used to implement various network protocols, including connection-oriented protocols (such as TCP) and connectionless protocols (such as UDP).
Members
Constructors
public Socket(SocketType socketType, ProtocolType protocolType)
Initializes a new instance of the Socket
class using the specified socket type and protocol type.
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.
Properties
public bool Blocking { get; set; }
Gets or sets a value that indicates whether a Socket
is in blocking or non-blocking mode.
public bool Connected { get; }
Gets a value that indicates whether the Socket
is connected to a remote host.
public EndPoint LocalEndPoint { get; }
Gets the local endpoint for the Socket
.
public EndPoint RemoteEndPoint { get; }
Gets the remote endpoint for the Socket
.
Methods
public void Bind(EndPoint localEP)
Binds a Socket
to a local endpoint.
public void Connect(string host, int port)
Establishes a connection to a remote device.
public int Receive(byte[] buffer)
Receives data from a connected Socket
into a buffer.
public int Send(byte[] buffer)
Sends data to a connected Socket
.
public void Close()
Releases all resources used by the Socket
.
Events
public event EventHandler Connected;
Occurs when a connection is established.
Remarks
The Socket
class provides a low-level interface to the network stack. You can use it to send and receive data over a network connection. For higher-level abstractions, consider using classes like TcpClient
or UdpClient
.
When working with sockets, it's crucial to manage resources properly. Always call Close()
or use a using
statement to ensure that socket resources are released. Error handling is also important, as network operations can fail for various reasons.
The Socket
class supports both synchronous and asynchronous operations. Asynchronous operations can improve application responsiveness by not blocking the calling thread while waiting for network events.
Exceptions
This class can throw the following exceptions:
SocketException
: Occurs when a socket error occurs during a socket operation.ArgumentNullException
: Occurs if a parameter is null.ArgumentOutOfRangeException
: Occurs if a parameter is out of the valid range.