拔下C#网络电缆 [英] C# Network Cable unplugged

查看:124
本文介绍了拔下C#网络电缆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

希望有人可以阐明我的问题.我有一个TCP客户端连接到端口上的IP地址.我需要一种方法来检测何时在服务器端或客户端上拔出网络电缆.互联网上的每个地方,论坛都在谈论Socket.Poll方式,但似乎不起作用吗?该代码位于一个计时器中,该计时器每秒滴答一次.

这是一个例子:

Hi Guys

Hope someone can shed some light on my problem. I have a TCP Client that connects to an IP adress on a port. I need a way to detect when a network cable was unplugged either on the server side or on the client side. Everywhere on the internet the forums talk about the Socket.Poll way but it does not seem to work? The code is in a Timer that ticks each second.

This is an example :

// Detect if client disconnected
if( tcp.Client.Poll( 0, SelectMode.SelectRead ) )
{
  byte[] buff = new byte[1];
  if( tcp.Client.Receive( buff, SocketFlags.Peek ) == 0 )
  {
    // Client disconnected
    bClosed = true;
  }
}


我发现可行的另一种方法是这种方法,但是我的CPU使用率不断提高:


Another way that I found that works is this but my CPU usage keeps rizing :

uint dummy = 0;

byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
//set keepalive on
BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
//interval time between last operation on socket and first checking. example:5000ms=5s
BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
//after first checking, socket will check serval times by 1000ms.
BitConverter.GetBytes((uint)1000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);

Socket socket = tcpclnt.Client;
socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);

if (tcpclnt.Client.Connected == false)
{
//DO 
}

推荐答案

这只是浪费时间和CPU周期,没有任何用处.在尝试发送消息之前知道电缆已拔出,这不会帮助您的程序高效运行.在网络通信期间,可以随时随地断开连接.这可能是您上次对其进行轮询后的一微秒.也许您应该尝试确切解释要解决的问题.
This is just wasting time and CPU cycles to no useful purpose. Knowing that the cable has been unplugged before trying to send a message will not help your program run efficiently. During network communication the connection can be broken at any point and at any time; which could be one microsecond after you last polled it. Maybe you should try and explain exactly what problem you are trying to solve.


这篇关于拔下C#网络电缆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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