TcpListener.AcceptSocket 方法

定義

接受暫止連接要求。

public:
 System::Net::Sockets::Socket ^ AcceptSocket();
public System.Net.Sockets.Socket AcceptSocket ();
member this.AcceptSocket : unit -> System.Net.Sockets.Socket
Public Function AcceptSocket () As Socket

傳回

Socket

用來傳送和接收資料的 Socket

例外狀況

尚未以呼叫 Start() 來啟動接聽項。

範例

在下列程式碼範例中 AcceptSocket ,會使用 方法傳回 Socket 。 這是 Socket 用來與新連線的用戶端通訊。

// Accepts the pending client connection and returns a socket for communciation.
Socket^ socket = tcpListener->AcceptSocket();
Console::WriteLine( "Connection accepted." );

String^ responseString = "You have successfully connected to me";

//Forms and sends a response string to the connected client.
array<Byte>^sendBytes = Encoding::ASCII->GetBytes( responseString );
int i = socket->Send( sendBytes );
Console::WriteLine( "Message Sent /> : {0}", responseString );

          // Accepts the pending client connection and returns a socket for communication.
           Socket socket = tcpListener.AcceptSocket();
            Console.WriteLine("Connection accepted.");

           string responseString = "You have successfully connected to me";

           //Forms and sends a response string to the connected client.
           Byte[] sendBytes = Encoding.ASCII.GetBytes(responseString);
           int i = socket.Send(sendBytes);
           Console.WriteLine("Message Sent /> : " + responseString);
' Accepts the pending client connection and returns a socket for communciation.
Dim socket As Socket = tcpListener.AcceptSocket()
Console.WriteLine("Connection accepted.")

Dim responseString As String = "You have successfully connected to me"

'Forms and sends a response string to the connected client.
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
Dim i As Integer = socket.Send(sendBytes)
Console.WriteLine(("Message Sent /> : " + responseString))

備註

AcceptSocket 是一種封鎖方法,會傳回 Socket 可用來傳送和接收資料的 。 如果您想要避免封鎖,請使用 Pending 方法來判斷傳入連線佇列中是否有可用的連線要求。

傳回的 會 Socket 以遠端主機的 IP 位址和埠號碼初始化。 您可以使用 類別中 Socket 提供的任何 SendReceive 方法,與遠端主機通訊。 當您使用 完成時 Socket ,請務必呼叫其 Close 方法。 如果您的應用程式相對簡單,請考慮使用 AcceptTcpClient 方法,而不是 AcceptSocket 方法。 TcpClient 提供簡單的方法,讓您在封鎖同步模式中透過網路傳送和接收資料。

注意

在應用程式中啟用網路追蹤時,這個成員會輸出追蹤資訊。 如需詳細資訊,請參閱.NET Framework中的網路追蹤

適用於

另請參閱