套接字问题(半开?) [英] Socket problem (half-open?)

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

问题描述

尊敬的读者,

我有一个Windows服务(客户端),该服务基本上应该24/7正常运行,但是有时连接断开.
基本上,发生的事情是我向该服务发送了一条命令,并且我将收到响应远程主机强行关闭了现有连接".

现在,我期望的是IsConnected函数(从计时器调用)会注意到该连接已断开并重新启动该连接,但实际上并没有注意到该连接已关闭.

Dear readers,

I have a windows service (client) which basically should be up 24/7, however sometimes the connection drops.
Basically what happens is that i send a command to the service, and i will get the response "An existing connection was forcibly closed by the remote host".

Now what i would expect is that the IsConnected function (called from timer) notices that the connection has dropped and restarts the connection but it doesn''t actually notice that the connection has closed.

private bool IsConnected(Socket socket)
{
    try
    {
        return !(socket.Poll(100, SelectMode.SelectRead) && socket.Available == 0);
    }
    catch (SocketException) { return false; }
}



但这似乎不起作用..
另一个想法是实际发送数据以保持活动状态,但是例如,如果在套接字正在传输文件的中间发生timer事件时,它将进入地狱.

插座:



But it doesn''t seem to work..
Another idea was to actually send data as a keep alive, but if the timer event raises while for example the socket is in the middle of transferring a file it goes to hell.

Socket:

clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);

     IPEndPoint ipEnd = new IPEndPoint(IPAddress.Loopback, 1500);

     clientSocket.Connect(ipEnd);



任何建议都非常欢迎,



Any suggestions are very welcome,

Thanks!

推荐答案

Scalee,

您的第一种方法是正确的,请尝试使用此方法

Hi Scalee,

Your First approach is correct one, try with this

private bool IsConnected(Socket socket)
{
    try
    {
        if(socket.Connected)
          return !(socket.Poll(100, SelectMode.SelectRead) && socket.Available == 0);
        else
          return false; 
    }
    catch (SocketException) { return false; }
}


这篇关于套接字问题(半开?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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