套接字断开通知方法 [英] socket disconnection notification method

查看:107
本文介绍了套接字断开通知方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅在客户断开连接时搜索可能的解决方案以进行个性化设置. 我发现了:

just searched for a posibble solution to indetify when the client disconnecets. i found this:

        public bool IsConnected( Socket s)
    {
        try
        {
            return !(s.Poll(1, SelectMode.SelectRead) &&s.Available == 0);
        }
        catch (SocketException) { return false; }
    }

我在我的主线程中使用一个while循环与thread.sleep(500)并运行Isconnectedmthod,当我通过Visual Studio运行它并单击停止调试时,它可以正常工作,但实际上它在服务器端程序中通知我我只是进入bin目录中的exe并启动它-确实的确通知我建立连接,但是当我关闭程序(通常是通过'x'按钮)或通过任务管理器关闭时,IsConnected方法显然仍然返回true ..... 即时通讯使用简单的TCP连接

im using a while loop in my main with thread.sleep(500) and running the Isconnectedmthod it works allright when i run it through the visual studio and when i click stop debugging it actually notify me in the server side program but when i just go to the exe in the bin directory and launch it-it's Indeed notify me for a connection but when i close the program (manually from the 'x' button) or through the task manager theIsConnected method apparently return still true..... im using a simple tcp connection

        client = new TcpClient();
         client.Connect("10.0.0.2", 10);

服务器:

Socket s = tcpClient.Client;
        while(true)
        {

            if (!IsConnected(s))


                MessageBox.Show("disconnected");
        }

(正在线程btw上运行).

(it's running on a thread btw).

有什么建议吗? 客户端关闭时,我什至试图关闭连接:

any suggestion guys? i even tried to close the connection when the client closes:

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {

        client.Close();
        s.Close();
        Environment.Exit(0);

    }

不知道该怎么办

推荐答案

您所要求的是不可能的.除非尝试在连接上发送,否则TCP将不会在连接上报告错误.如果您的程序曾经执行过所有操作,则它将永远不会注意到该连接不再存在.

What you are asking for is not possible. TCP will not report an error on the connection unless an attempt is made to send on the connection. If all your program ever does is receive, it will never notice that the connection no longer exists.

此规则有一些与平台有关的例外,但没有一个涉及远程端点的简单消失.

There are some platform-dependent exceptions to this rule, but none involving the simple disappearance of the remote endpoint.

客户端断开连接的正确方法是使用关闭"操作正常关闭连接.在.NET中,这意味着客户端代码调用Socket.Shutdown(SocketShutdown.Send).然后,客户端必须继续接收,直到服务器调用Socket.Shutdown(SocketShutdown.Both).请注意,对于启动关闭的端点,关闭原因"通常是发送",对于确认并完成关闭的端点,通常是两者".

The correct way for a client to disconnect is for it to gracefully close the connection with a "shutdown" operation. In .NET, this means the client code calls Socket.Shutdown(SocketShutdown.Send). The client must then continue to receive until the server calls Socket.Shutdown(SocketShutdown.Both). Note that the shutdown "reason" is generally "send" for the endpoint initiating the closure, and "both" for the endpoint acknowledging and completing the closure.

每个端点都将通过以0作为该操作的字节计数返回值的接收操作完成,来检测到另一个端点已关闭其端点.在完成双向平滑关闭之前,任何端点都不应真正关闭套接字(即调用Socket.Close()). IE.每个端点都调用了Socket.Shutdown() ,它们看到了一个零字节的接收操作完成.

Each endpoint will detect that the other endpoint has shutdown its end by the completion of a receive operation with 0 as the byte count return value for that operation. Neither endpoint should actually close the socket (i.e. call Socket.Close()) until this two-way graceful closure has completed. I.e. each endpoint has both called Socket.Shutdown() and seen a zero-byte receive operation completion.

以上是正常关闭的工作方式,它应该成为服务器/客户端交互的规范.当然,事情确实会破裂.客户端可能会崩溃,网络可能会断开连接,等等.通常,正确的做法是尽可能长时间地延迟对此类问题的识别;例如,只要服务器和客户端不需要实际通信,那么暂时的网络中断就不会导致错误.在这种情况下,强迫一个人是没有意义的.

The above is how graceful closure works, and it should be the norm for server/client interactions. Of course, things do break. A client could crash, the network might be disconnected, etc. Typically, the right thing to do is to delay recognition of such problems as long as possible; for example, as long as the server and client have no need to actually communicate, then a temporary network outage should not cause an error. Forcing one is pointless in that case.

换句话说,不要添加代码来尝试检测连接失败.为了获得最大的可靠性,让网络尝试自行恢复.

In other words, don't add code to try to detect a connection failure. For maximum reliability, let the network try to recover on its own.

在一些不太常见的情况下,希望尽早检测到连接失败.在这些情况下,您可以在套接字上启用保持活动状态"(以强制通过连接发送数据,从而检测连接中断),请参阅

In some less-common cases, it is desirable to detect connection failures earlier. In these cases, you can enable "keep alive" on the socket (to force data to be sent over the connection, thus detecting interruptions in the connection…see SocketOptionName.KeepAlive) or implement some timeout mechanism (to force the connection to fail if no data is sent after some period of time). I would generally recommend against the use of this kind of technique, but it's a valid approach in some cases.

这篇关于套接字断开通知方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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