Socket 類別

定義

實作 Berkeley 通訊端介面。Implements the Berkeley sockets interface.

public ref class Socket : IDisposable
public class Socket : IDisposable
type Socket = class
    interface IDisposable
Public Class Socket
Implements IDisposable
繼承
Socket
實作

範例

下列程式碼範例會示範如何使用 Socket 類別,將資料傳送至 HTTP 伺服器並接收回應。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);
   String^ strRetPage = "";
   
   // 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;
   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 );
   
   s->Dispose();

   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 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];
        string page = "";
        
        // Create a socket connection with the specified server and port.
        using(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;
            page = "Default HTML page on " + server + ":\r\n";

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

Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Net.Sockets

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]
      Dim page As String = ""  
      
      ' 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.
      page = "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
End Class  

備註

Socket 類別為網路通訊提供了一組豐富的方法和屬性。The Socket class provides a rich set of methods and properties for network communications. Socket 類別可讓您使用 ProtocolType 列舉中列出的任何通訊協定來執行同步和非同步資料傳輸。The Socket class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the ProtocolType enumeration.

Socket 類別會遵循非同步方法的 .NET Framework 命名模式。The Socket class follows the .NET Framework naming pattern for asynchronous methods. 例如,同步 Receive 方法會對應至非同步 BeginReceiveEndReceive 方法。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.

  • 如果您使用以連接為導向的通訊協定(例如 TCP),您的伺服器就可以使用 Listen 方法來接聽連接。If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the Listen method. Accept 方法會處理任何連入的連線要求,並傳回可用來與遠端主機通訊資料的 SocketThe Accept method processes any incoming connection requests and returns a Socket that you can use to communicate data with the remote host. 使用這個傳回的 Socket 來呼叫 SendReceive 方法。Use this returned Socket to call the Send or Receive method. 如果您想要指定本機 IP 位址和埠號碼,在呼叫 Listen 方法之前,請先呼叫 Bind 方法。Call the Bind method prior to calling the Listen method if you want to specify the local IP address and port number. 如果您想要讓基礎服務提供者為您指派免費埠,請使用埠號碼0。Use a port number of zero if you want the underlying service provider to assign a free port for you. 如果您想要連接到接聽主機,請呼叫 Connect 方法。If you want to connect to a listening host, call the Connect method. 若要傳達資料,請呼叫 SendReceive 方法。To communicate data, call the Send or Receive method.

  • 如果您使用的是無連線通訊協定,例如 UDP,則完全不需要接聽連接。If you are using a connectionless protocol such as UDP, you do not need to listen for connections at all. 呼叫 ReceiveFrom 方法以接受任何傳入的資料包。Call the ReceiveFrom method to accept any incoming datagrams. 使用 SendTo 方法,將資料包傳送至遠端主機。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.

當您完成傳送和接收資料時,請使用 Shutdown 方法來停用 SocketWhen you are finished sending and receiving data, use the Shutdown method to disable the Socket. 呼叫 Shutdown之後,請呼叫 Close 方法來釋放與 Socket相關聯的所有資源。After calling Shutdown, call the Close method to release all resources associated with the Socket.

Socket 類別可讓您使用 SetSocketOption 方法來設定您的 SocketThe Socket class allows you to configure your Socket using the SetSocketOption method. 使用 GetSocketOption 方法來取得這些設定。Retrieve these settings using the GetSocketOption method.

注意

如果您要撰寫一個相對簡單的應用程式,而不需要最大效能,請考慮使用 TcpClientTcpListenerUdpClientIf you are writing a relatively simple application and do not require maximum performance, consider using TcpClient, TcpListener, and UdpClient. 這些類別提供更簡單且更容易使用的介面來 Socket 通訊。These classes provide a simpler and more user-friendly interface to Socket communications.

建構函式

Socket(AddressFamily, SocketType, ProtocolType)

使用指定的通訊協定家族 (Family)、通訊端類型和通訊協定,初始化 Socket 類別的新執行個體。Initializes a new instance of the Socket class using the specified address family, socket type and protocol.

Socket(SocketInformation)

使用從 Socket 傳回的指定值,初始化 DuplicateAndClose(Int32) 類別的新執行個體。Initializes a new instance of the Socket class using the specified value returned from DuplicateAndClose(Int32).

Socket(SocketType, ProtocolType)

使用指定的通訊端類型和通訊協定,初始化 Socket 類別的新執行個體。Initializes a new instance of the Socket class using the specified socket type and protocol.

屬性

AddressFamily

取得 Socket 的通訊協定家族 (Family)。Gets the address family of the Socket.

Available

取得已從網路接收且可供讀取的資料量。Gets the amount of data that has been received from the network and is available to be read.

Blocking

取得或設定值,指出 Socket 是否處於區塊模式。Gets or sets a value that indicates whether the Socket is in blocking mode.

Connected

取得值,指出上一個 SocketSend 作業是否將 Receive 連接至遠端主機。Gets a value that indicates whether a Socket is connected to a remote host as of the last Send or Receive operation.

DontFragment

取得或設定 Boolean 值,指定 Socket 是否允許將網際網路通訊協定 (IP) 資料包分散。Gets or sets a Boolean value that specifies whether the Socket allows Internet Protocol (IP) datagrams to be fragmented.

DualMode

取得或設定 Boolean 值,指定 Socket 是否為適用於 IPv4 和 IPv6 的雙重模式通訊端。Gets or sets a Boolean value that specifies whether the Socket is a dual-mode socket used for both IPv4 and IPv6.

EnableBroadcast

取得或設定 Boolean 值,指定 Socket 是否可以傳送或接收廣播封包。Gets or sets a Boolean value that specifies whether the Socket can send or receive broadcast packets.

ExclusiveAddressUse

取得或設定 Boolean 值,指定 Socket 是否只允許一個處理序繫結至通訊埠。Gets or sets a Boolean value that specifies whether the Socket allows only one process to bind to a port.

Handle

取得 Socket 的作業系統處理。Gets the operating system handle for the Socket.

IsBound

取得值,指出 Socket 是否繫結至特定的本機通訊埠。Gets a value that indicates whether the Socket is bound to a specific local port.

LingerState

取得或設定值,指定 Socket 是否會延遲關閉通訊端,以嘗試傳送所有暫止資料。Gets or sets a value that specifies whether the Socket will delay closing a socket in an attempt to send all pending data.

LocalEndPoint

取得本機端點。Gets the local endpoint.

MulticastLoopback

取得或設定值,指定輸出多點傳送封包是否會傳遞至傳送應用程式。Gets or sets a value that specifies whether outgoing multicast packets are delivered to the sending application.

NoDelay

取得或設定 Boolean 值,指定資料流 Socket 是否使用 Nagle 演算法。Gets or sets a Boolean value that specifies whether the stream Socket is using the Nagle algorithm.

OSSupportsIPv4

指出基礎作業系統和網路配置器是否支援網際網路通訊協定第 4 版 (IPv4)。Indicates whether the underlying operating system and network adaptors support Internet Protocol version 4 (IPv4).

OSSupportsIPv6

指出基礎作業系統和網路配置器是否支援網際網路通訊協定第 6 版 (IPv6)。Indicates whether the underlying operating system and network adaptors support Internet Protocol version 6 (IPv6).

ProtocolType

取得 Socket 的通訊協定 (Protocol) 類型。Gets the protocol type of the Socket.

ReceiveBufferSize

取得或設定值,指定 Socket 之接收緩衝區的大小。Gets or sets a value that specifies the size of the receive buffer of the Socket.

ReceiveTimeout

取得或設定值,指定同步 Receive 呼叫逾時之前的時間長度。Gets or sets a value that specifies the amount of time after which a synchronous Receive call will time out.

RemoteEndPoint

取得遠端端點。Gets the remote endpoint.

SafeHandle

取得 SafeSocketHandle,表示目前 Socket 物件所封裝的通訊端控制代碼。Gets a SafeSocketHandle that represents the socket handle that the current Socket object encapsulates.

SendBufferSize

取得或設定值,指定 Socket 之傳送緩衝區的大小。Gets or sets a value that specifies the size of the send buffer of the Socket.

SendTimeout

取得或設定值,指定同步 Send 呼叫逾時之前的時間長度。Gets or sets a value that specifies the amount of time after which a synchronous Send call will time out.

SocketType

取得 Socket 的類型。Gets the type of the Socket.

SupportsIPv4

取得值,指出 IPv4 支援是否可用並在目前的主機上啟用。Gets a value indicating whether IPv4 support is available and enabled on the current host.

SupportsIPv6

取得值,指出「架構」是否對某些已過時 Dns 成員支援 IPv6。Gets a value that indicates whether the Framework supports IPv6 for certain obsolete Dns members.

Ttl

取得或設定值,指定 Socket 傳送之網際網路通訊協定 (IP) 封包的存留時間 (TTL) 值。Gets or sets a value that specifies the Time To Live (TTL) value of Internet Protocol (IP) packets sent by the Socket.

UseOnlyOverlappedIO

指定通訊端是否只應使用重疊的 I/O 模式。Specifies whether the socket should only use Overlapped I/O mode.

方法

Accept()

建立新建立連接的新 SocketCreates a new Socket for a newly created connection.

AcceptAsync(SocketAsyncEventArgs)

開始非同步作業以接受連入的連接嘗試。Begins an asynchronous operation to accept an incoming connection attempt.

BeginAccept(AsyncCallback, Object)

開始非同步作業以接受連入的連接嘗試。Begins an asynchronous operation to accept an incoming connection attempt.

BeginAccept(Int32, AsyncCallback, Object)

開始非同步作業以接收連入連線嘗試,並接收用戶端應用程式傳送的第一個資料區塊。Begins an asynchronous operation to accept an incoming connection attempt and receives the first block of data sent by the client application.

BeginAccept(Socket, Int32, AsyncCallback, Object)

開始非同步作業以接收指定通訊端的連入連線嘗試,並接收用戶端應用程式傳送的第一個資料區塊。Begins an asynchronous operation to accept an incoming connection attempt from a specified socket and receives the first block of data sent by the client application.

BeginConnect(EndPoint, AsyncCallback, Object)

開始遠端主機連接的非同步要求。Begins an asynchronous request for a remote host connection.

BeginConnect(IPAddress, Int32, AsyncCallback, Object)

開始遠端主機連接的非同步要求。Begins an asynchronous request for a remote host connection. 此主機是由 IPAddress 和連接埠號碼所指定。The host is specified by an IPAddress and a port number.

BeginConnect(IPAddress[], Int32, AsyncCallback, Object)

開始遠端主機連接的非同步要求。Begins an asynchronous request for a remote host connection. 主機是由 IPAddress 陣列和通訊埠編號指定。The host is specified by an IPAddress array and a port number.

BeginConnect(String, Int32, AsyncCallback, Object)

開始遠端主機連接的非同步要求。Begins an asynchronous request for a remote host connection. 此主機是由主機名稱和連接埠號碼指定。The host is specified by a host name and a port number.

BeginDisconnect(Boolean, AsyncCallback, Object)

開始非同步要求,以中斷遠端端點的連接。Begins an asynchronous request to disconnect from a remote endpoint.

BeginReceive(Byte[], Int32, Int32, SocketFlags, AsyncCallback, Object)

開始從已連接的 Socket 非同步接收資料。Begins to asynchronously receive data from a connected Socket.

BeginReceive(Byte[], Int32, Int32, SocketFlags, SocketError, AsyncCallback, Object)

開始從已連接的 Socket 非同步接收資料。Begins to asynchronously receive data from a connected Socket.

BeginReceive(IList<ArraySegment<Byte>>, SocketFlags, AsyncCallback, Object)

開始從已連接的 Socket 非同步接收資料。Begins to asynchronously receive data from a connected Socket.

BeginReceive(IList<ArraySegment<Byte>>, SocketFlags, SocketError, AsyncCallback, Object)

開始從已連接的 Socket 非同步接收資料。Begins to asynchronously receive data from a connected Socket.

BeginReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object)

開始從指定的網路裝置非同步接收資料。Begins to asynchronously receive data from a specified network device.

BeginReceiveMessageFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object)

使用指定的 SocketFlags,開始以非同步方式接收指定位元組數目的資料至資料緩衝區所指定位置,並儲存端點和封包資訊。Begins to asynchronously receive the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint and packet information.

BeginSend(Byte[], Int32, Int32, SocketFlags, AsyncCallback, Object)

非同步傳送資料至已連接的 SocketSends data asynchronously to a connected Socket.

BeginSend(Byte[], Int32, Int32, SocketFlags, SocketError, AsyncCallback, Object)

非同步傳送資料至已連接的 SocketSends data asynchronously to a connected Socket.

BeginSend(IList<ArraySegment<Byte>>, SocketFlags, AsyncCallback, Object)

非同步傳送資料至已連接的 SocketSends data asynchronously to a connected Socket.

BeginSend(IList<ArraySegment<Byte>>, SocketFlags, SocketError, AsyncCallback, Object)

非同步傳送資料至已連接的 SocketSends data asynchronously to a connected Socket.

BeginSendFile(String, AsyncCallback, Object)

使用 Socket 旗標,將檔案 fileName 傳送至已連接的 UseDefaultWorkerThread 物件。Sends the file fileName to a connected Socket object using the UseDefaultWorkerThread flag.

BeginSendFile(String, Byte[], Byte[], TransmitFileOptions, AsyncCallback, Object)

將檔案和資料緩衝區以非同步方式傳送至已連接的 Socket 物件。Sends a file and buffers of data asynchronously to a connected Socket object.

BeginSendTo(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object)

以非同步方式將資料傳送至特定的遠端主機。Sends data asynchronously to a specific remote host.

Bind(EndPoint)

使 Socket 與本機端點建立關聯。Associates a Socket with a local endpoint.

CancelConnectAsync(SocketAsyncEventArgs)

取消遠端主機連接的非同步要求。Cancels an asynchronous request for a remote host connection.

Close()

關閉 Socket 連接並釋放所有相關資源。Closes the Socket connection and releases all associated resources.

Close(Int32)

關閉 Socket 連線,並釋放所有具指定逾時的關聯資源,以允許傳送佇列的資料。Closes the Socket connection and releases all associated resources with a specified timeout to allow queued data to be sent.

Connect(EndPoint)

建立與遠端主機的連線。Establishes a connection to a remote host.

Connect(IPAddress, Int32)

建立與遠端主機的連線。Establishes a connection to a remote host. 此主機是由 IP 位址和連接埠號碼所指定。The host is specified by an IP address and a port number.

Connect(IPAddress[], Int32)

建立與遠端主機的連線。Establishes a connection to a remote host. 主機是由 IP 位址陣列和連接埠號碼所指定。The host is specified by an array of IP addresses and a port number.

Connect(String, Int32)

建立與遠端主機的連線。Establishes a connection to a remote host. 此主機是由主機名稱和連接埠號碼指定。The host is specified by a host name and a port number.

ConnectAsync(SocketAsyncEventArgs)

開始與遠端主機連接的非同步要求。Begins an asynchronous request for a connection to a remote host.

ConnectAsync(SocketType, ProtocolType, SocketAsyncEventArgs)

開始與遠端主機連接的非同步要求。Begins an asynchronous request for a connection to a remote host.

Disconnect(Boolean)

關閉通訊端連線並允許重複使用通訊端。Closes the socket connection and allows reuse of the socket.

DisconnectAsync(SocketAsyncEventArgs)

開始非同步要求,以中斷遠端端點的連接。Begins an asynchronous request to disconnect from a remote endpoint.

Dispose()

釋放 Socket 類別目前的執行個體所使用的全部資源。Releases all resources used by the current instance of the Socket class.

Dispose(Boolean)

釋放 Socket 所使用的 Unmanaged 資源,並選擇性處置 Managed 資源。Releases the unmanaged resources used by the Socket, and optionally disposes of the managed resources.

DuplicateAndClose(Int32)

複製目標處理序的通訊端參考,並關閉這個處理序的通訊端。Duplicates the socket reference for the target process, and closes the socket for this process.

EndAccept(Byte[], IAsyncResult)

以非同步方式接受連入連線嘗試,並建立新的 Socket 物件,以處理遠端主機通訊。Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. 這個方法會傳回包含已傳輸之初始資料的緩衝區。This method returns a buffer that contains the initial data transferred.

EndAccept(Byte[], Int32, IAsyncResult)

以非同步方式接受連入連線嘗試,並建立新的 Socket 物件,以處理遠端主機通訊。Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. 這個方法會傳回包含已傳輸之初始資料和位元組數的緩衝區。This method returns a buffer that contains the initial data and the number of bytes transferred.

EndAccept(IAsyncResult)

以非同步方式接受連入的連接嘗試,並建立新的 Socket 來處理遠端主機通訊。Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.

EndConnect(IAsyncResult)

結束擱置的非同步連接要求。Ends a pending asynchronous connection request.

EndDisconnect(IAsyncResult)

結束暫止非同步中斷連接要求。Ends a pending asynchronous disconnect request.

EndReceive(IAsyncResult)

結束擱置的非同步讀取。Ends a pending asynchronous read.

EndReceive(IAsyncResult, SocketError)

結束擱置的非同步讀取。Ends a pending asynchronous read.

EndReceiveFrom(IAsyncResult, EndPoint)

從指定的端點結束暫止的非同步讀取。Ends a pending asynchronous read from a specific endpoint.

EndReceiveMessageFrom(IAsyncResult, SocketFlags, EndPoint, IPPacketInformation)

從指定的端點結束暫止的非同步讀取。Ends a pending asynchronous read from a specific endpoint. 這個方法還會比 EndReceiveFrom(IAsyncResult, EndPoint) 提供更多的封包資訊。This method also reveals more information about the packet than EndReceiveFrom(IAsyncResult, EndPoint).

EndSend(IAsyncResult)

結束暫止的非同步傳送。Ends a pending asynchronous send.

EndSend(IAsyncResult, SocketError)

結束暫止的非同步傳送。Ends a pending asynchronous send.

EndSendFile(IAsyncResult)

結束檔案的暫止非同步傳送。Ends a pending asynchronous send of a file.

EndSendTo(IAsyncResult)

結束暫止的非同步傳送至指定的位置。Ends a pending asynchronous send to a specific location.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Finalize()

釋放 Socket 類別所使用的資源。Frees resources used by the Socket class.

GetHashCode()

傳回 Socket 執行個體的雜湊值。Returns a hash value for a Socket instance.

GetSocketOption(SocketOptionLevel, SocketOptionName)

傳回指定 Socket 選項的值,表示為物件。Returns the value of a specified Socket option, represented as an object.

GetSocketOption(SocketOptionLevel, SocketOptionName, Byte[])

傳回指定的 Socket 選項設定,表示為位元組陣列。Returns the specified Socket option setting, represented as a byte array.

GetSocketOption(SocketOptionLevel, SocketOptionName, Int32)

以陣列傳回指定 Socket 選項的值。Returns the value of the specified Socket option in an array.

GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
IOControl(Int32, Byte[], Byte[])

使用數值控制碼,設定 Socket 的低階作業模式。Sets low-level operating modes for the Socket using numerical control codes.

IOControl(IOControlCode, Byte[], Byte[])

使用 Socket 列舉型別指定控制碼,以設定 IOControlCode 的低階作業模式。Sets low-level operating modes for the Socket using the IOControlCode enumeration to specify control codes.

Listen(Int32)

Socket 置於接聽狀態。Places a Socket in a listening state.

MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
Poll(Int32, SelectMode)

決定 Socket 的狀態。Determines the status of the Socket.

Receive(Byte[])

從已繫結的 Socket 接收資料至接收緩衝區中。Receives data from a bound Socket into a receive buffer.

Receive(Byte[], Int32, Int32, SocketFlags)

使用指定的 Socket,從已繫結的 SocketFlags 將指定的位元組數接收到接收緩衝區的指定位移位置。Receives the specified number of bytes from a bound Socket into the specified offset position of the receive buffer, using the specified SocketFlags.

Receive(Byte[], Int32, Int32, SocketFlags, SocketError)

使用指定的 Socket,從已繫結的 SocketFlags 接收資料至接收緩衝區中。Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.

Receive(Byte[], Int32, SocketFlags)

使用指定的 Socket,從已繫結的 SocketFlags 將指定位元組數的資料接收至接收緩衝區中。Receives the specified number of bytes of data from a bound Socket into a receive buffer, using the specified SocketFlags.

Receive(Byte[], SocketFlags)

使用指定的 Socket,從已繫結的 SocketFlags 接收資料至接收緩衝區中。Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.

Receive(IList<ArraySegment<Byte>>)

從已繫結的 Socket 接收資料至接收緩衝區清單中。Receives data from a bound Socket into the list of receive buffers.

Receive(IList<ArraySegment<Byte>>, SocketFlags)

使用指定的 Socket,從已繫結的 SocketFlags 接收資料至接收緩衝區清單中。Receives data from a bound Socket into the list of receive buffers, using the specified SocketFlags.

Receive(IList<ArraySegment<Byte>>, SocketFlags, SocketError)

使用指定的 Socket,從已繫結的 SocketFlags 接收資料至接收緩衝區清單中。Receives data from a bound Socket into the list of receive buffers, using the specified SocketFlags.

Receive(Span<Byte>)

從已繫結的 Socket 接收資料至接收緩衝區中。Receives data from a bound Socket into a receive buffer.

Receive(Span<Byte>, SocketFlags)

使用指定的 Socket,從已繫結的 SocketFlags 接收資料至接收緩衝區中。Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.

Receive(Span<Byte>, SocketFlags, SocketError)

使用指定的 Socket,從已繫結的 SocketFlags 接收資料至接收緩衝區中。Receives data from a bound Socket into a receive buffer, using the specified SocketFlags.

ReceiveAsync(SocketAsyncEventArgs)

開始非同步要求,以接收來自已連接的 Socket 物件的資料。Begins an asynchronous request to receive data from a connected Socket object.

ReceiveFrom(Byte[], EndPoint)

接收資料包至資料緩衝區中,並儲存端點。Receives a datagram into the data buffer and stores the endpoint.

ReceiveFrom(Byte[], Int32, Int32, SocketFlags, EndPoint)

使用指定的 SocketFlags,將指定的資料位元組數目接收至資料緩衝區的指定位置,並儲存端點。Receives the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint.

ReceiveFrom(Byte[], Int32, SocketFlags, EndPoint)

使用指定的 SocketFlags,接收指定的位元組數至資料緩衝區中,並儲存端點。Receives the specified number of bytes into the data buffer, using the specified SocketFlags, and stores the endpoint.

ReceiveFrom(Byte[], SocketFlags, EndPoint)

使用指定的 SocketFlags,接收資料包至資料緩衝區中,並儲存端點。Receives a datagram into the data buffer, using the specified SocketFlags, and stores the endpoint.

ReceiveFromAsync(SocketAsyncEventArgs)

開始從指定的網路裝置非同步接收資料。Begins to asynchronously receive data from a specified network device.

ReceiveMessageFrom(Byte[], Int32, Int32, SocketFlags, EndPoint, IPPacketInformation)

使用指定的 SocketFlags,將指定的資料位元組數目接收至資料緩衝區的指定位置,並儲存端點及封包資訊。Receives the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint and packet information.

ReceiveMessageFromAsync(SocketAsyncEventArgs)

使用指定的 SocketFlags,開始以非同步方式將指定之位元組數目的資料,接收至資料緩衝區的指定位置,並儲存端點和封包資訊。Begins to asynchronously receive the specified number of bytes of data into the specified location in the data buffer, using the specified SocketFlags, and stores the endpoint and packet information.

Select(IList, IList, IList, Int32)

判斷一或多個通訊端的狀態。Determines the status of one or more sockets.

Send(Byte[])

傳送資料至已連接的 SocketSends data to a connected Socket.

Send(Byte[], Int32, Int32, SocketFlags)

從指定位移開始,並使用指定的 SocketFlags,將資料的指定位元組數傳送到連接的 SocketSends the specified number of bytes of data to a connected Socket, starting at the specified offset, and using the specified SocketFlags.

Send(Byte[], Int32, Int32, SocketFlags, SocketError)

從指定的位移開始並使用指定的 Socket,將指定的資料位元組數傳送至已連接的 SocketFlagsSends the specified number of bytes of data to a connected Socket, starting at the specified offset, and using the specified SocketFlags

Send(Byte[], Int32, SocketFlags)

使用指定的 Socket,傳送指定的資料位元組數至已連接的 SocketFlagsSends the specified number of bytes of data to a connected Socket, using the specified SocketFlags.

Send(Byte[], SocketFlags)

使用指定的 Socket,傳送資料至已連接的 SocketFlagsSends data to a connected Socket using the specified SocketFlags.

Send(IList<ArraySegment<Byte>>)

將清單中的緩衝區集合傳送至連接的 SocketSends the set of buffers in the list to a connected Socket.

Send(IList<ArraySegment<Byte>>, SocketFlags)

使用指定的 Socket,將清單中的緩衝區集合傳送至連接的 SocketFlagsSends the set of buffers in the list to a connected Socket, using the specified SocketFlags.

Send(IList<ArraySegment<Byte>>, SocketFlags, SocketError)

使用指定的 Socket,將清單中的緩衝區集合傳送至連接的 SocketFlagsSends the set of buffers in the list to a connected Socket, using the specified SocketFlags.

Send(ReadOnlySpan<Byte>)

傳送資料至已連接的 SocketSends data to a connected Socket.

Send(ReadOnlySpan<Byte>, SocketFlags)

使用指定的 Socket,傳送資料至已連接的 SocketFlagsSends data to a connected Socket using the specified SocketFlags.

Send(ReadOnlySpan<Byte>, SocketFlags, SocketError)

使用指定的 Socket,傳送資料至已連接的 SocketFlagsSends data to a connected Socket using the specified SocketFlags.

SendAsync(SocketAsyncEventArgs)

將資料以非同步方式傳送至已連接的 Socket 物件。Sends data asynchronously to a connected Socket object.

SendFile(String)

使用 Socket 傳輸旗標,將檔案 fileName 傳送至已連接的 UseDefaultWorkerThread 物件。Sends the file fileName to a connected Socket object with the UseDefaultWorkerThread transmit flag.

SendFile(String, Byte[], Byte[], TransmitFileOptions)

使用指定的 TransmitFileOptions 值,將檔案 fileName 和資料緩衝區傳送到連接的 Socket 物件。Sends the file fileName and buffers of data to a connected Socket object using the specified TransmitFileOptions value.

SendPacketsAsync(SocketAsyncEventArgs)

以非同步的方式將檔案的集合或記憶體中資料緩衝區傳送至連接的 Socket 物件。Sends a collection of files or in memory data buffers asynchronously to a connected Socket object.

SendTo(Byte[], EndPoint)

傳送資料至指定的端點。Sends data to the specified endpoint.

SendTo(Byte[], Int32, Int32, SocketFlags, EndPoint)

從緩衝區中的指定位置開始且使用指定的 SocketFlags,傳送指定位元組數目的資料至指定的端點。Sends the specified number of bytes of data to the specified endpoint, starting at the specified location in the buffer, and using the specified SocketFlags.

SendTo(Byte[], Int32, SocketFlags, EndPoint)

使用指定的 SocketFlags,傳送指定位元組數目的資料至指定的端點。Sends the specified number of bytes of data to the specified endpoint using the specified SocketFlags.

SendTo(Byte[], SocketFlags, EndPoint)

使用指定的 SocketFlags,傳送資料至特定端點。Sends data to a specific endpoint using the specified SocketFlags.

SendToAsync(SocketAsyncEventArgs)

以非同步方式將資料傳送至特定的遠端主機。Sends data asynchronously to a specific remote host.

SetIPProtectionLevel(IPProtectionLevel)

設定通訊端上的 IP 保護層級。Set the IP protection level on a socket.

SetSocketOption(SocketOptionLevel, SocketOptionName, Boolean)

將指定的 Socket 選項設為指定的 Boolean 值。Sets the specified Socket option to the specified Boolean value.

SetSocketOption(SocketOptionLevel, SocketOptionName, Byte[])

將指定的 Socket 選項設定為指定值,表示為位元組陣列。Sets the specified Socket option to the specified value, represented as a byte array.

SetSocketOption(SocketOptionLevel, SocketOptionName, Int32)

將指定 Socket 選項設定為指定的整數值。Sets the specified Socket option to the specified integer value.

SetSocketOption(SocketOptionLevel, SocketOptionName, Object)

將指定的 Socket 選項設定為指定值,表示為物件。Sets the specified Socket option to the specified value, represented as an object.

Shutdown(SocketShutdown)

暫停 Socket 上的傳送和接收作業。Disables sends and receives on a Socket.

ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

IDisposable.Dispose()

釋放 Socket 所使用的所有資源。Releases all resources used by the Socket.

擴充方法

AcceptAsync(Socket)

執行非同步作業,以接受通訊端上的連入連線嘗試。Performs an asynchronous operation on to accept an incoming connection attempt on the socket.

AcceptAsync(Socket, Socket)

執行非同步作業,以接受通訊端上的連入連線嘗試。Performs an asynchronous operation on to accept an incoming connection attempt on the socket.

ConnectAsync(Socket, EndPoint)

建立與遠端主機的連線。Establishes a connection to a remote host.

ConnectAsync(Socket, IPAddress, Int32)

建立與遠端主機的連線。Establishes a connection to a remote host. 此主機是由 IP 位址和連接埠號碼所指定。The host is specified by an IP address and a port number.

ConnectAsync(Socket, IPAddress[], Int32)

建立與遠端主機的連線。Establishes a connection to a remote host. 主機是由 IP 位址陣列和連接埠號碼所指定。The host is specified by an array of IP addresses and a port number.

ConnectAsync(Socket, String, Int32)

建立與遠端主機的連線。Establishes a connection to a remote host. 此主機是由主機名稱和連接埠號碼指定。The host is specified by a host name and a port number.

ReceiveAsync(Socket, ArraySegment<Byte>, SocketFlags)

從已連線的通訊端擷取資料。Receives data from a connected socket.

ReceiveAsync(Socket, IList<ArraySegment<Byte>>, SocketFlags)

從已連線的通訊端擷取資料。Receives data from a connected socket.

ReceiveAsync(Socket, Memory<Byte>, SocketFlags, CancellationToken)

從已連線的通訊端擷取資料。Receives data from a connected socket.

ReceiveFromAsync(Socket, ArraySegment<Byte>, SocketFlags, EndPoint)

從指定的網路裝置接收資料。Receives data from a specified network device.

ReceiveMessageFromAsync(Socket, ArraySegment<Byte>, SocketFlags, EndPoint)

使用指定的 SocketFlags,將指定的資料位元組數目接收至資料緩衝區的指定位置,並儲存端點及封包資訊。Receives the specified number of bytes of data into the specified location of the data buffer, using the specified SocketFlags, and stores the endpoint and packet information.

SendAsync(Socket, ArraySegment<Byte>, SocketFlags)

將資料傳送到已連線的通訊端。Sends data to a connected socket.

SendAsync(Socket, IList<ArraySegment<Byte>>, SocketFlags)

將資料傳送到已連線的通訊端。Sends data to a connected socket.

SendAsync(Socket, ReadOnlyMemory<Byte>, SocketFlags, CancellationToken)

將資料傳送到已連線的通訊端。Sends data to a connected socket.

SendToAsync(Socket, ArraySegment<Byte>, SocketFlags, EndPoint)

以非同步方式將資料傳送至特定的遠端主機。Sends data asynchronously to a specific remote host.

安全性

SocketPermission
建立連出連線或接受傳入要求。To establish an outgoing connection or accept an incoming request.

適用於

執行緒安全性

這個類別的實例是安全線程。Instances of this class are thread safe.

另請參閱