System.Net.Sockets.Socket class

This article provides supplementary remarks to the reference documentation for this API.

The Socket class provides a rich set of methods and properties for network communications. The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration.

The Socket class follows the .NET naming pattern for asynchronous methods. For example, the synchronous Receive method corresponds to the asynchronous ReceiveAsync variants.

Use the following methods for synchronous operation mode:

  • If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the Listen method. The Accept method processes any incoming connection requests and returns a Socket that you can use to communicate data with the remote host. Use this returned Socket to call the Send or Receive method. Call the Bind method prior to calling the Listen method if you want to specify the local IP address and port number. Use a port number of zero if you want the underlying service provider to assign a free port for you. If you want to connect to a listening host, call the Connect method. To communicate data, call the Send or Receive method.
  • If you are using a connectionless protocol such as UDP, you do not need to listen for connections at all. Call the ReceiveFrom method to accept any incoming datagrams. Use the SendTo method to send datagrams to a remote host.

To process communications asynchronously, use the following methods:

  • If you are using a connection-oriented protocol such as TCP, use ConnectAsync to connect with a listening host. Use SendAsync or ReceiveAsync to communicate data asynchronously. Incoming connection requests can be processed using AcceptAsync.
  • If you are using a connectionless protocol such as UDP, you can use SendToAsync to send datagrams, and ReceiveFromAsyncto receive datagrams.

If you perform multiple asynchronous operations on a socket, they do not necessarily complete in the order in which they are started.

When you are finished sending and receiving data, use the Shutdown method to disable the Socket. After calling Shutdown, call the Close method to release all resources associated with the Socket.

The Socket class allows you to configure your Socket using the SetSocketOption method. Retrieve these settings using the GetSocketOption method.