Socket Class

July 28, 2014

Implements the Berkeley sockets interface.

System.Object
  System.Net.Sockets.Socket

Namespace:  System.Net.Sockets
Assembly:  System.Net (in System.Net.dll)

public class Socket : IDisposable

The Socket type exposes the following members.

  NameDescription
Public methodSocketInitializes a new instance of the Socket class using the specified address family, socket type and protocol.
Top

  NameDescription
Public propertyAddressFamilyGets the address family of the Socket.
Public propertyConnectedGets a value that indicates whether a Socket is connected to a remote host as of the last operation.
Public propertyLocalEndPointGets the local endpoint that contains the local IP address and port number to which the socket is bound. This is the endpoint that the socket is using for communications.
Public propertyNoDelayGets or sets a Boolean value that specifies whether the Socket is using the Nagle algorithm.
Public propertyStatic memberOSSupportsIPv4Gets a value indicating whether IPv4 support is available and enabled on the current host.
Public propertyStatic memberOSSupportsIPv6Gets a value indicating whether IPv6 support is available and enabled on the current host.
Public propertyProtocolTypeGets the protocol type of the Socket.
Public propertyReceiveBufferSizeGets or sets a value that specifies the size of the receive buffer of the Socket.
Public propertyRemoteEndPointGets the remote endpoint.
Public propertySendBufferSizeGets or sets a value that specifies the size of the send buffer of the Socket.
Public propertyTtlGets or sets a value that specifies the Time To Live (TTL) value of Internet Protocol (IP) packets sent by the Socket.
Top

  NameDescription
Public methodAcceptAsyncBegins an asynchronous operation to accept an incoming connection attempt.
Public methodBindAssociates a socket with a specific local endpoint. You do not need to call Bind before using the ConnectAsync method unless you need to use a specific local endpoint.
Public methodStatic memberCancelConnectAsyncCancels an outstanding asynchronous socket operation for a remote host connection.
Public methodClose()Closes the Socket connection and releases all associated resources.
Public methodClose(Int32)Closes the Socket connection and releases all associated resources with a specified timeout to allow queued data to be sent.
Public methodConnectAsync(SocketAsyncEventArgs)Begins an asynchronous request for a remote host connection.
Public methodStatic memberConnectAsync(SocketType, ProtocolType, SocketAsyncEventArgs)Begins an asynchronous request for a remote host connection.
Public methodDispose()Releases the unmanaged resources used by the Socket, and optionally disposes of the managed resources.
Protected methodDispose(Boolean)Releases the unmanaged resources used by the Socket, and optionally disposes of the managed resources.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeFrees resources used by the Socket class. (Overrides Object.Finalize().)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodListenListens for incoming connection attempts.
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodReceiveAsyncBegins an asynchronous request to receive data from a connected Socket object.
Public methodReceiveFromAsyncBegins an asynchronous request to receive data from a specific remote host.
Public methodSendAsyncSends data asynchronously to a connected Socket object.
Public methodSendToAsyncSends data asynchronously to a specific remote host.
Public methodShutdownDisables sends and receives on a Socket.
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public Extension MethodAssociateToNetworkInterfaceSets information about a network interface by associating it with a new set of network interface information. (Defined by SocketExtensions.)
Public Extension MethodGetCurrentNetworkInterfaceGets all available information about the network interface. (Defined by SocketExtensions.)
Public Extension MethodSetNetworkPreferenceSets the preference for a network interface to use either cellular or non-cellular technology. (Defined by SocketExtensions.)
Public Extension MethodSetNetworkRequirementSets the requirement for a network interface to use either cellular or non-cellular technology. (Defined by SocketExtensions.)
Top

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

 For Windows Phone OS 7.1, the supported ProtocolType values are the TCP and UDP protocol. For Windows Phone OS 7.1, TCP unicast, UDP unicast, and UDP multicast clients are supported.

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.

For sockets, the security policy system affects cross-domain network access. A security policy is required for any connections from sockets.


public class Example
{
  static ManualResetEvent clientDone = new ManualResetEvent(false);

  public static void Demo(System.Windows.Controls.TextBlock outputBlock)
  {

      SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();

      // NOTE: This is a fake end point. 
      // You must change this to a valid URL or you will get an exception below.
      DnsEndPoint hostEntry = new DnsEndPoint("http://www.contoso.com", 80);

      // Create a socket and connect to the server
      Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

      socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArg_Completed);

      socketEventArg.RemoteEndPoint = hostEntry;
      socketEventArg.UserToken = sock;
      sock.ConnectAsync(socketEventArg);
      clientDone.WaitOne();
  }

  // A single callback is used for all socket operations. 
  // This method forwards execution on to the correct handler 
  // based on the type of completed operation
  static void SocketEventArg_Completed(object sender, SocketAsyncEventArgs e)
  {
      switch (e.LastOperation)
      {
          case SocketAsyncOperation.Connect:
              ProcessConnect(e);
              break;

          case SocketAsyncOperation.Receive:
              ProcessReceive(e);
              break;

          case SocketAsyncOperation.Send:
              ProcessSend(e);
              break;

          default:
              throw new Exception("Invalid operation completed");
      }
  }

  // Called when a ConnectAsync operation completes
  private static void ProcessConnect(SocketAsyncEventArgs e)
  {
      if (e.SocketError == SocketError.Success)
      {
          // Successfully connected to the server

          // Send 'Hello World' to the server
          byte[] buffer = Encoding.UTF8.GetBytes("Hello World");
          e.SetBuffer(buffer, 0, buffer.Length);
          Socket sock = e.UserToken as Socket;
          bool willRaiseEvent = sock.SendAsync(e);

          if (!willRaiseEvent)
          {
              ProcessSend(e);
          }
      }
      else
      {
          throw new SocketException((int)e.SocketError);
      }
  }

      // Called when a ReceiveAsync operation completes
      // </summary>
  private static void ProcessReceive(SocketAsyncEventArgs e)
  {
      if (e.SocketError == SocketError.Success)
      {
          // Received data from server

          // Data has now been sent and received from the server. 
          // Disconnect from the server
          Socket sock = e.UserToken as Socket;
          sock.Shutdown(SocketShutdown.Send);
          sock.Close();
          clientDone.Set();
      }
      else
      {
          throw new SocketException((int)e.SocketError);
      }
  }


  // Called when a SendAsync operation completes
  private static void ProcessSend(SocketAsyncEventArgs e)
  {
      if (e.SocketError == SocketError.Success)
      {
          // Sent "Hello World" to the server successfully

          //Read data sent from the server
          Socket sock = e.UserToken as Socket;
          bool willRaiseEvent = sock.ReceiveAsync(e);

          if (!willRaiseEvent)
          {
              ProcessReceive(e);
          }
      }
      else
      {
          throw new SocketException((int)e.SocketError);
      }
  }
}


Windows Phone OS

Supported in: 8.1, 8.0, 7.1

Windows Phone

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Show:
© 2014 Microsoft