c# 非阻塞算法_如何在C#中进行非阻塞套接字调用以确定连接状态?

Socket上Connected属性的MSDN文档说明如下:

The value of the Connected property

reflects the state of the connection

as of the most recent operation. If

you need to determine the current

state of the connection,make a

nonblocking,zero-byte Send call. If

the call returns successfully or

throws a WAEWOULDBLOCK error code

(10035),then the socket is still

connected; otherwise,the socket is no

longer connected.

我需要确定连接的当前状态 – 如何进行非阻塞,零字节发送调用?

解决方法

Socket.Connected属性(至少.NET 3.5版本)的MSDN文档底部的示例显示了如何执行此操作:

// .Connect throws an exception if unsuccessful

client.Connect(anEndPoint);

// This is how you can determine whether a socket is still connected.

bool blockingState = client.Blocking;

try

{

byte [] tmp = new byte[1];

client.Blocking = false;

client.Send(tmp,0);

Console.WriteLine("Connected!");

}

catch (SocketException e)

{

// 10035 == WSAEWOULDBLOCK

if (e.NativeErrorCode.Equals(10035))

Console.WriteLine("Still Connected,but the Send would block");

else

{

Console.WriteLine("Disconnected: error code {0}!",e.NativeErrorCode);

}

}

finally

{

client.Blocking = blockingState;

}

Console.WriteLine("Connected: {0}",client.Connected);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值