Export (0) Print
Expand All

Socket Class

Implements the Berkeley sockets interface.

For a list of all members of this type, see Socket Members.

System.Object
   System.Net.Sockets.Socket

[Visual Basic]
Public Class Socket
   Implements IDisposable
[C#]
public class Socket : IDisposable
[C++]
public __gc class Socket : public IDisposable
[JScript]
public class Socket implements IDisposable

Thread Safety

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

Remarks

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 would like to specify the local IP address and port number. If you do not call Bind, the underlying service provider will assign these values for you. You can later use the LocalEndPoint property to identify the IP address and port number assigned to your Socket. If you would like 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 methods. Retrieve these settings using the GetSocketOption methods.

Note   If you are writing a relatively simple application and only require synchronous data transfer, consider using TcpClient, TcpListener, and UdpClient. These classes provide a simpler and more user-friendly interface to Socket communications.

Example

[Visual Basic, C#, C++] The following example shows how the Socket class can be used to send data to an HTTP server and receive the response.

[Visual Basic] 
Imports System
Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports Microsoft.VisualBasic

Public Class GetSocket
   
   Private Shared Function ConnectSocket(server As String, port As Integer) As Socket
      Dim s As Socket = Nothing
      Dim hostEntry As IPHostEntry = Nothing      
     
         ' 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 host IP Address is not compatible with the address family
         ' (typical in the IPv6 case).
      Dim address As IPAddress
 
        For Each address In  hostEntry.AddressList
            Dim endPoint As New IPEndPoint(address, port)
            Dim tempSocket As New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
      
            tempSocket.Connect(endPoint)
            
            If tempSocket.Connected Then
               s = tempSocket
               Exit For
            End If

         Next address
      
      Return s
   End Function 
   
   
   ' This method requests the home page content for the specified server.
   
   Private Shared Function SocketSendReceive(server As String, port As Integer) As String
      'Set up variables and String to write to the server.
      Dim ascii As Encoding = Encoding.ASCII
      Dim request As String = "GET / HTTP/1.1" + ControlChars.Cr + ControlChars.Lf + "Host: " + server + ControlChars.Cr + ControlChars.Lf + "Connection: Close" + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf
      Dim bytesSent As [Byte]() = ascii.GetBytes(request)
      Dim bytesReceived(255) As [Byte]
      
      ' Create a socket connection with the specified server and port.
      Dim s As Socket = ConnectSocket(server, port)
      
      If s Is Nothing Then
         Return "Connection failed"
      End If 
      ' Send request to the server.
      s.Send(bytesSent, bytesSent.Length, 0)
      
      ' Receive the server  home page content.
      Dim bytes As Int32
      
      ' Read the first 256 bytes.
      Dim page as [String] = "Default HTML page on " + server + ":" + ControlChars.Cr + ControlChars.Lf
      
      ' The following will block until the page is transmitted.
      Do
         bytes = s.Receive(bytesReceived, bytesReceived.Length, 0)
         page = page + ascii.ASCII.GetString(bytesReceived, 0, bytes)
      Loop While bytes > 0
      
      Return page
   End Function 
   
   'Entry point which delegates to C-style main Private Function
   Public Overloads Shared Sub Main()
      Main(System.Environment.GetCommandLineArgs())
   End Sub
   
   
   Overloads Private Shared Sub Main(args() As String)
      Dim host As String
      Dim port As Integer = 80
      
      If args.Length = 1 Then
         ' 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)
      End If 
      
      Dim result As String = SocketSendReceive(host, port)
      
      Console.WriteLine(result)
   End Sub 'Main
End Class  


[C#] 
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

public class GetSocket
{
    private static Socket ConnectSocket(string server, int port)
    {
        Socket s = null;
        IPHostEntry hostEntry = null;
        
        // 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).
        foreach(IPAddress address in hostEntry.AddressList)
        {
            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket tempSocket = 
                new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            tempSocket.Connect(ipe);

            if(tempSocket.Connected)
            {
                s = tempSocket;
                break;
            }
            else
            {
                continue;
            }
        }
        return s;
    }

    // This method requests the home page content for the specified server.
    private static string SocketSendReceive(string server, int port) 
    {
        string request = "GET / HTTP/1.1\r\nHost: " + server + 
            "\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 == null)
            return ("Connection failed");
      
        // Send request to the server.
        s.Send(bytesSent, bytesSent.Length, 0);  
        
        // Receive the server home page content.
        int bytes = 0;
        string page = "Default HTML page on " + server + ":\r\n";

        // The following will block until te page is transmitted.
        do {
            bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
            page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
        }
        while (bytes > 0);
        
        return page;
    }
    
    public static void Main(string[] args) 
    {
        string host;
        int port = 80;

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

        string result = SocketSendReceive(host, port); 
        Console.WriteLine(result);
    }
}


[C++] 
#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);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Net.Sockets

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: System (in System.dll)

.NET Framework Security: 

  • SocketPermission to establish an outgoing connection or accept an incoming request.

See Also

Socket Members | System.Net.Sockets Namespace

Show:
© 2014 Microsoft