Freigeben über


Socket-Klasse

Implementiert die Berkeley-Sockets-Schnittstelle.

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

Syntax

'Declaration
Public Class Socket
    Implements IDisposable
'Usage
Dim instance As Socket
public class Socket : IDisposable
public ref class Socket : IDisposable
public class Socket implements IDisposable
public class Socket implements IDisposable

Hinweise

Die Socket-Klasse stellt eine große Anzahl von Methoden und Eigenschaften für die Netzwerkkommunikation bereit. Mit der Socket-Klasse können Sie sowohl synchrone als auch asynchrone Datenübertragungen mit einem der in der ProtocolType-Enumeration aufgelisteten Kommunikationsprotokolle ausführen. Die Socket-Klasse folgt dem .NET Framework-Benennungsmuster für asynchrone Methoden. Beispielsweise entspricht die synchrone Receive-Methode der asynchronen BeginReceive-Methode und der asynchronen EndReceive-Methode.

Wenn die Anwendung nicht mehr als einen Ausführungsthread benötigt, können Sie die folgenden Methoden verwenden, die für den synchronen Vorgangsmodus bereitstehen.

  • Wenn Sie ein verbindungsorientiertes Protokoll wie TCP verwenden, kann der Server mit der Listen-Methode Verbindungen überwachen. Die Accept-Methode verarbeitet eingehende Verbindungsanforderungen und gibt einen Socket zurück, den Sie verwenden können, um Daten mit dem Remotehost auszutauschen. Mit diesem zurückgegebenen Socket können Sie die Send-Methode oder die Receive-Methode aufrufen. Rufen Sie vor dem Aufruf der Listen-Methode die Bind-Methode auf, wenn Sie die lokale IP-Adresse und Anschlussnummer angeben möchten. Verwenden Sie die Anschlussnummer 0 (null), wenn der zugrunde liegende Dienstanbieter einen freien Anschluss für Sie zuweisen soll. Rufen Sie die Connect-Methode auf, wenn Sie eine Verbindung mit einem überwachenden Host herstellen möchten. Die Daten können durch Aufruf der Send-Methode oder der Receive-Methode übertragen werden.

  • Wenn Sie ein verbindungsloses Protokoll wie UDP verwenden, müssen Sie keine Verbindungen überwachen. Eingehende Datagramme können durch Aufruf der ReceiveFrom-Methode angenommen werden. Mit der SendTo-Methode können Sie Datagramme an einen Remotehost senden.

Verwenden Sie die folgenden Methoden, um die Kommunikation mit separaten Ausführungsthreads zu verarbeiten. Die folgenden Methoden wurden für den asynchronen Vorgangsmodus konzipiert.

  • Wenn Sie ein verbindungsorientiertes Protokoll wie TCP verwenden, können Sie mit der Socket-Methode, der BeginConnect-Methode und der EndConnect-Methode Verbindungen mit einem überwachenden Host herstellen. Die asynchrone Datenkommunikation kann mit der BeginSend-Methode und der EndSend-Methode bzw. der BeginReceive-Methode und der EndReceive-Methode stattfinden. Eingehende Verbindungsanforderungen können mit BeginAccept und EndAccept verarbeitet werden.

  • Wenn Sie ein verbindungsloses Protokoll wie UDP verwenden, können Sie mit BeginSendTo und EndSendTo Datagramme senden und mit BeginReceiveFrom und EndReceiveFrom Datagramme empfangen.

Wenn Sie mehrere asynchrone Vorgänge für ein Socket ausführen, werden diese nicht notwendigerweise in der Startreihenfolge abgeschlossen.

Nach dem Senden bzw. Empfangen von Daten deaktivieren Sie den Socket mit der Shutdown-Methode. Rufen Sie nach der Shutdown-Methode die Close-Methode auf, um alle dem Socket zugeordneten Ressourcen freizugeben.

Die Socket-Klasse ermöglicht das Konfigurieren des Socket mit der SetSocketOption-Methode. Rufen Sie die entsprechenden Einstellungen mit der GetSocketOption-Methode ab.

Hinweis

Wenn Sie eine eher einfache Anwendung schreiben und nicht die maximale Leistung benötigen, bietet sich die Verwendung von TcpClient, TcpListener und UdpClient an. Diese Klassen stellen eine einfachere und benutzerfreundlichere Schnittstelle für die Socket-Kommunikation bereit.

Hinweis zu Windows Mobile für Pocket PC, Windows Mobile für Smartphone, Windows CE: Nicht alle Socketoptionen werden auf allen Gerätebetriebssystemen unterstützt.

Beispiel

Im folgenden Codebeispiel wird veranschaulicht, wie mit der Socket-Klasse Daten an einen HTTP-Server gesendet werden können und die Antwort empfangen werden kann. In diesem Beispiel wird die Ausführung blockiert, bis die ganze Seite empfangen wurde.

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.GetHostEntry(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 + Encoding.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  
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.GetHostEntry(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);
    }
}
#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 );
}
import System.*;
import System.Text.*;
import System.IO.*;
import System.Net.*;
import 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).
        for (int iCtr = 0; iCtr < hostEntry.get_AddressList().length; iCtr++) {
            IPAddress address = hostEntry.get_AddressList()[iCtr];
            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket tempSocket = new Socket(ipe.get_AddressFamily(),
                SocketType.Stream, ProtocolType.Tcp);
            tempSocket.Connect(ipe);
            if (tempSocket.get_Connected()) {
                s = tempSocket;
                break;
            }
            else {
                continue;
            }
        }

        return s;
    } //ConnectSocket

    // 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";
        System.Byte bytesSent[] = 
            (System.Byte[])Encoding.get_ASCII().GetBytes(request);
        System.Byte bytesReceived[] = new System.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((ubyte[])bytesSent, bytesSent.length, (SocketFlags)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((ubyte[])bytesReceived,
                bytesReceived.length, (SocketFlags)0);
            page = page + Encoding.get_ASCII().GetString(
                (ubyte[])bytesReceived, 0, bytes);
        } while (bytes > 0);
        return page;
    } //SocketSendReceive

    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);
    } //main
} //GetSocket

.NET Framework-Sicherheit

  • SocketPermission  zum Herstellen einer ausgehenden Verbindung oder Annehmen einer eingehenden Anforderung.

Vererbungshierarchie

System.Object
  System.Net.Sockets.Socket

Threadsicherheit

Instanzen dieser Klasse sind threadsicher.

Plattformen

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile für Pocket PC, Windows Mobile für Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework unterstützt nicht alle Versionen sämtlicher Plattformen. Eine Liste der unterstützten Versionen finden Sie unter Systemanforderungen.

Versionsinformationen

.NET Framework

Unterstützt in: 2.0, 1.1, 1.0

.NET Compact Framework

Unterstützt in: 2.0, 1.0

Siehe auch

Referenz

Socket-Member
System.Net.Sockets-Namespace