侦听TCP Server应用程序的以太网电缆拔出事件 [英] Listening for an Ethernet Cable Unplugging Event for a TCP Server Application

查看:85
本文介绍了侦听TCP Server应用程序的以太网电缆拔出事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#TCP服务器应用程序。当TCP客户端与服务器断开连接时,我检测到断开连接,但如何检测电缆拔出事件?当我拔出以太网电缆时,无法检测到断开连接。

I have a C# TCP server application. I detect disconnections of TCP clients when they disconnect from server but how can I detect a cable unplug event? When I unplug the ethernet cable I can't detect the disconnection.

推荐答案

您可能要应用 pinging功能,如果TCP连接丢失,将失败。使用以下代码向Socket添加扩展方法:

You might want to apply "pinging" functionality, that will fail if there is TCP connection lose. Use this code to add extension method to Socket:

using System.Net.Sockets;

namespace Server.Sockets {
    public static class SocketExtensions {
        public static bool IsConnected(this Socket socket) {
            try {
                return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
            } catch(SocketException) {
                return false;
            }
        }
    }
}

方法如果没有可用的连接,将返回false。即使您在Reveice / Send方法上没有SocketException,也应该检查是否有连接。
请记住,如果您遇到了异常,该错误消息与连接丢失有关,则您不再需要检查连接。

此方法用于套接字时

Method will return false if there is no connection available. It should work to check if there is or no connection even if you had no SocketExceptions on Reveice / Send methods. Bear in mind that if you had exception that had error message that is related to connection lose, then you don't need check for connection anymore.
This method is meant to be used when socket is looks like connected but might be not like in your case.

用法:

if (!socket.IsConnected()) {
    /* socket is disconnected */
}

这篇关于侦听TCP Server应用程序的以太网电缆拔出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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