Export (0) Print
Expand All

Socket Class

Implements the Berkeley sockets interface.

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

public ref class Socket : IDisposable

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 Framework naming pattern for asynchronous methods. For example, the synchronous Receive method corresponds to the asynchronous BeginReceive and EndReceive methods.

If your application only requires one thread during execution, use the following methods, which are designed 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 using separate threads during execution, use the following methods, which are designed for asynchronous operation mode.

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.

NoteNote:

If you are writing a relatively simple application and do not require maximum performance, consider using TcpClient, TcpListener, and UdpClient. These classes provide a simpler and more user-friendly interface to Socket communications.

Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note: Not all socket options are supported on all device operating systems.

The following code example shows how the Socket class can be used to send data to an HTTP server and receive the response. This example blocks until the entire page is received.

#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Collections;
Socket^ ConnectSocket( String^ server, int port )
{
   Socket^ s = nullptr;
   IPHostEntry^ hostEntry = nullptr;

   // Get host related information.
   hostEntry = Dns::Resolve( server );

   // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid 
   // an exception that occurs when the host IP Address is not compatible with the address family 
   // (typical in the IPv6 case).
   IEnumerator^ myEnum = hostEntry->AddressList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      IPAddress^ address = safe_cast<IPAddress^>(myEnum->Current);
      IPEndPoint^ endPoint = gcnew IPEndPoint( address,port );
      Socket^ tmpS = gcnew Socket( endPoint->AddressFamily,SocketType::Stream,ProtocolType::Tcp );
      tmpS->Connect( endPoint );
      if ( tmpS->Connected )
      {
         s = tmpS;
         break;
      }
      else
      {
         continue;
      }
   }

   return s;
}


// This method requests the home page content for the specified server.
String^ SocketSendReceive( String^ server, int port )
{
   String^ request = String::Concat( "GET / HTTP/1.1\r\nHost: ", server, "\r\nConnection: Close\r\n\r\n" );
   array<Byte>^bytesSent = Encoding::ASCII->GetBytes( request );
   array<Byte>^bytesReceived = gcnew array<Byte>(256);

   // Create a socket connection with the specified server and port.
   Socket^ s = ConnectSocket( server, port );
   if ( s == nullptr )
      return ("Connection failed");


   // Send request to the server.
   s->Send( bytesSent, bytesSent->Length, static_cast<SocketFlags>(0) );

   // Receive the server home page content. 
   int bytes = 0;
   String^ strRetPage = String::Concat( "Default HTML page on ", server, ":\r\n" );
   do
   {
      bytes = s->Receive( bytesReceived, bytesReceived->Length, static_cast<SocketFlags>(0) );
      strRetPage = String::Concat( strRetPage, Encoding::ASCII->GetString( bytesReceived, 0, bytes ) );
   }
   while ( bytes > 0 );

   return strRetPage;
}

int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   String^ host;
   int port = 80;
   if ( args->Length == 1 )

   // If no server name is passed as argument to this program,  
   // use the current host name as default.
   host = Dns::GetHostName();
   else
      host = args[ 1 ];

   String^ result = SocketSendReceive( host, port );
   Console::WriteLine( result );
}
#using <mscorlib.dll>
#using <System.dll>
using namespace System;
using namespace System::Text;
using namespace System::IO;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Collections;

Socket * ConnectSocket(String* server, int port) {
    Socket* s = 0;
    IPHostEntry* hostEntry = 0;

    // Get host related information.
    hostEntry = Dns::Resolve(server);

    // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
    // an exception that occurs when the host IP Address is not compatible with the address family
    // (typical in the IPv6 case).
    IEnumerator* myEnum = hostEntry->AddressList->GetEnumerator();
    while (myEnum->MoveNext()) 
    {
        IPAddress* address = __try_cast<IPAddress*>(myEnum->Current);
        IPEndPoint* endPoint = new IPEndPoint(address, port);
        Socket* tmpS = new Socket(endPoint->AddressFamily, SocketType::Stream, ProtocolType::Tcp);
        tmpS->Connect(endPoint);
        if (tmpS->Connected) 
        {
            s = tmpS;
            break;
        } else
        {
            continue;
        }
    }

    return s;
}

// This method requests the home page content for the specified server.

String* SocketSendReceive(String* server, int port) 
{
    String* request = String::Concat(S"GET / HTTP/1.1\r\nHost: ", server,
        S"\r\nConnection: Close\r\n\r\n");
    Byte bytesSent[] = Encoding::ASCII->GetBytes(request);
    Byte bytesReceived[] = new Byte[256];

    // Create a socket connection with the specified server and port.
    Socket* s = ConnectSocket(server, port);
    if (s == 0)
        return (S"Connection failed");

    // Send request to the server.
    s->Send(bytesSent, bytesSent->Length, static_cast<SocketFlags>(0));

    // Receive the server home page content.
    int bytes = 0;
    String* strRetPage = String::Concat(S"Default HTML page on ", server, S":\r\n");

    do {
        bytes = s->Receive(bytesReceived, bytesReceived->Length, static_cast<SocketFlags>(0));
        strRetPage = String::Concat(strRetPage, Encoding::ASCII->GetString(bytesReceived, 0, bytes));
    }
    while (bytes > 0);

    return strRetPage;
}

int main() {
    String* args[] = Environment::GetCommandLineArgs();
    String* host;
    int port = 80;

    if (args->Length == 1)
        // If no server name is passed as argument to this program, 
        // use the current host name as default.
        host = Dns::GetHostName();
    else
        host = args[1];

    String* result = SocketSendReceive(host, port);
    Console::WriteLine(result);
}

  • SocketPermission 

    To establish an outgoing connection or accept an incoming request.

System::Object
  System.Net.Sockets::Socket

Instances of this class are thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft