本文介绍了C ++套接字-Winsock连接丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在VC ++ 2008应用程序中使用winsock2 API.
当应用程序正在运行并且套接字一直处于读写状态时,我拔下网络电缆以强制出现网络问题.
为了检查连接是否断开,我只向套接字发送了0个字节,但是我仍然返回0而不是SOCKET_ERROR.
有人知道如何检查连接是否断开吗?

I''m using the winsock2 API in my VC++ 2008 app.
When the application is running and the socket is connected all the time reading/writing, I unplug the network cable to force a network problem.
In order to check if the connection is down I just send 0 bytes to the socket, but I still returns 0 instead of SOCKET_ERROR.
Does anyone know how to check if the connection is down?

推荐答案

A ----- R ----- R ---- R ---- B
        \----R-----R---/


而且由于坐在A上的人无法控制它们之间所有链接的整个状态,所以A本地没有任何事件可以单独证明A到B的可达性.

拔下电缆只会使网卡脱机,但不会对IP(即无连接)产生任何影响.
当然,您可以-使用适当的OS API-检查卡的状态,但是即使您发现它向上"也不意味着B可以到达.

如果在TCP套接字上操作,则必须信任TCP来检测错误.
只需尝试发送需要确认的内容(因此,大于0个字节),TCP(不接收它)将一遍又一遍地重新发送数据,直到最大重传超时(通常为40秒).到那时,TCP将失败,套接字将报告错误.
不要试图逃避之前的等待,也不要缩短超时时间:由于存在以下原因,计时器就存在了:-如果发生暂时的不可访问性-TCP必须能够维持套接字,从而允许基础网络路由找到替代方法路径而不会中断会话.


And since who sits on A cannot have the control of the entire state of all the links in between, there is no event local to A that can alone demonstrate A to B reachability.

Unplugging the cable simply makes the network card offline, but doesn''t have any effect on IP (that is connectionless).
Of course, you can -with appropriate OS API- check the status of the card, but even if you find it "up" doesn''t mean B is reachable.

If you operate on a TCP socket, you have to trust TCP in detecting errors.
Just try send something that requires an acknowledge (hence, more then 0 bytes), and TCP, not receiving it, will resend the data over and over up to the maximum retransmit timeout (usually 40 seconds). At that point TCP will fail and the socket will report the error.
Don''t try to escape the waiting before, or make the timeout shorter: that timer are there for the good reason that -if a temporary unreachability happens- TCP must be able to sustain the socket allowing the underlying network routing to find an alternative path without breaking the session.




tcp_keepalive KeepAlive;
DWORD dJunk;

//使用套接字级别保持活动大约5分钟
//除非这样做,否则Microsoft不会关闭套接字
//如果电缆/VPN断开2小时.
KeepAlive.onoff = 1;
KeepAlive.keepalivetime = 60000;
KeepAlive.keepaliveinterval = 60000;

WSAIoctl(soc,SIO_KEEPALIVE_VALS,& KeepAlive,sizeof(KeepAlive),NULL,0,& dJunk,NULL,NULL);



tcp_keepaliveKeepAlive;
DWORDdJunk;

//Use socket level keep alive for about 5 minutes
//Unless this is done Microsoft will not close the socket
//in the event of a cable / VPN disconnection for 2 hours.
KeepAlive.onoff = 1;
KeepAlive.keepalivetime = 60000;
KeepAlive.keepaliveinterval = 60000;

WSAIoctl( soc, SIO_KEEPALIVE_VALS, &KeepAlive, sizeof( KeepAlive ), NULL, 0, &dJunk, NULL, NULL );





如果等待消息,则上面的内容将导致套接字(在工作线程中)超时.



Above will cause a socket ( in a worker thread ) to time out if its waiting for a message.


这篇关于C ++套接字-Winsock连接丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 11:48
查看更多