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用于发送和接收数据。

例外

侦听器尚未通过调用 Start()来启动。

示例

在下面的代码示例中, AcceptSocket 该方法用于返回一个 Socket。 这 Socket 用于与新连接的客户端通信。


// 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 地址和端口号初始化的。 可以使用类中Send提供的任何ReceiveSocket方法与远程主机通信。 使用 Socket完该方法后,请务必调用其 Close 方法。 如果应用程序相对简单,请考虑使用 AcceptTcpClient 该方法而不是 AcceptSocket 方法。 TcpClient 提供了在阻止同步模式下通过网络发送和接收数据的简单方法。

注释

在应用程序中启用网络跟踪时,此成员将输出跟踪信息。 有关详细信息,请参阅 .NET Framework 中的 Network Tracing

适用于

另请参阅