C#:检查套接字是否与服务器建立活动连接? [英] C#: Checking if a socket has a active connection to the server?

查看:50
本文介绍了C#:检查套接字是否与服务器建立活动连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种合法的方式来告诉套接字是否与服务器建立了连接.如果他们尚未连接,或者客户端或服务器已将其关闭,则此功能无效.

I'm trying to find a legitamate wya to tell if the socket has a connection with the server. This becomes invalid if they haven't connected yet, or either the client or server has closed it.

在我使用此套接字对象连接到服务器之前,此方法当前返回null.谁能向我解释为什么这样做以及如何解决?

This method is currently returning null before I ever connect to the server using this socket object. Can anyone explain to me why it does that, and how I can fix it?

private static bool IsConnected(Socket socket)
{
    return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}

推荐答案

了解套接字是否有效的 only 方法是发送一些东西并取回一些东西.其他所有方法都是谎言. .Available 仅告诉您当前的读取缓冲区中是否有数据.状态是……充其量是不可靠的.套接字可能会在不通知操作系统的情况下死亡.套接字可以被网络硬件人为地欺骗为活着的"-试图防止临时的网络中断(特别是对于wifi或移动用户)切断所有套接字;但是有时该设备永远不会回来,并且中间的设备没有注意到.这意味着即使TCP级别的套接字中断检测也是不可靠.

The only way to know if a socket is valid is to send something and get something back. Every other way is a lie. .Available only tells you whether there is data in the current read-buffer. The status is ... at best unreliable. Sockets can die without the OS noticing. Sockets can be artificially spoofed as "alive" by network hardware - in an attempt to prevent temporary network blips (especially for wifi or mobile users) severing all their sockets; but sometimes that device never comes back, and the device in the middle doesn't notice. This means that even TCP-level broken-socket detection is unreliable.

所以:发送某种测试消息并取回一些东西.这是唯一的方式.

So: send some kind of test message and get something back. That is the only way.

这篇关于C#:检查套接字是否与服务器建立活动连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆