Pending Method

本文介绍 .NET Framework 中 TcpListener 类的 Pending 方法,该方法用于判断是否有待处理的连接请求。文章提供了 C# 示例代码,演示如何使用 Pending 方法检查客户端连接请求,并在存在连接请求时调用 AcceptTcpClient 方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pending Method

.NET Framework Class Library
TcpListener.Pending Method

Determines if there are pending connection requests.

[C#]
public bool Pending();
Return Value

true if connections are pending; otherwise, false.

Exceptions
Exception TypeCondition
InvalidOperationExceptionThe listener has not been started with a call to Start.
Remarks

This non-blocking method determines if there are any pending connection requests. Because the AcceptSocket and AcceptTcpClient methods block execution until Start has queued an incoming connection request, the Pending method can be used to determine if connections are available before attempting to accept them.

Example

[C#] The following example checks the Pending method. If a connection request is waiting to be accepted, then then a call to AcceptTcpClient is made.

[C#]

      try{
// Use the Pending method to poll the underlying socket instance for client connection requests.
    IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener tcpListener =  new TcpListener(ipAddress, portNumber);
tcpListener.Start();

  if (!tcpListener.Pending()) {

  Console.WriteLine("Sorry, no connection requests have arrived");
 
             }
             else{

     //Accept the pending client connection and return a TcpClient object initialized for communication.
     TcpClient tcpClient = tcpListener.AcceptTcpClient();
     // Using the RemoteEndPoint property.
     Console.WriteLine("I am listening for connections on " +
                                 IPAddress.Parse(((IPEndPoint)tcpListener.LocalEndpoint).Address.ToString()) +
                                    "on port number " + ((IPEndPoint)tcpListener.LocalEndpoint).Port.ToString());

Requirements

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值