如何检查套接字连接是否有效? [英] How to check whether socket connection is alive ?

查看:416
本文介绍了如何检查套接字连接是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在Windows上开发客户端服务器应用程序.
我正在使用Winsock API.

有什么功能可以检查套接字连接的状态吗?

我程序的流程就像.



1)建立与服务器的连接
2)用插座做些什么
3)保持空闲状态
4)将内容发送到服务器.

在第4步中将任何数据发送到服务器时,有什么方法可以让我检查连接是否仍然有效吗?

Hi,

I am developing a client server application on windows.
I am using winsock api.

Is ther any function by which i can check the status of the socket connection.

flow of my program is like.



1 ) Establish a connection to the server
2 ) Do something with the socket
3 ) Keep idle
4 ) Send something to the server.

While sending any data to server in 4th step, is ther any way for me to check whether the connection is still alive ?

推荐答案

好吧,我将对所有这些求和并添加另一个选项:

1)通常,在第4步中,如果连接未激活,则send()将返回错误. (请注意:即使您没有向其中发送任何流量,您的连接也可以无限期保持活动状态.)

2)如果您使用keep-alive选项打开了套接字,则TCP将自动发送心跳消息以监视连接,如果连接不活跃,则将其关闭.从内存来看,保持活动是Winsock和大多数UNIX/Linux实现的默认选项.

3)我还可以使用的另一种选择是将我自己的心跳数据包发送到连接中(两种方式).这还具有一个优点,例如路由器之类的中间设备不会太聪明,也不会将连接丢弃为非活动状态-因为它总是有一些(较小的)流量.

4)最后,要检查连接是否正常运行,可以将recv与MSG_PEEK选项一起使用,例如:
Ok, I will just sum it all up and add one more option:

1) Generally, in your 4th step, if the connection is not alive, your send() will return an error. (Note: your connection can remain active indefinitely, even if you send no traffic into it).

2) If you''ve opened the socket with a keep-alive option, TCP will automatically send a heartbeat message to monitor the connection and close it if it is not alive. From memory, keep-alive is a default option with Winsock and most UNIX/Linux implementations.

3) The other option which I use a fair bit is to send my own hearbeat packet into connection (both ways). This also has the advantage that intermediate devices such as routers don''t try to be too smart and drop the connection as inactive - as it always has some (small) traffic.

4) And finally, to check for connection being alive, you can use recv with MSG_PEEK option, something like:
char data;
recv(socket,&data,1, MSG_PEEK);//read one byte


但请确保您处于非阻止模式. (注意-使用PEEK可以确保接收的数据不出队,并且可以通过正确的接收例程进行读取/处理).这是Ulimiate TCP/IP使用的方法.


but make sure you are in non-blocking mode. (Note - using PEEK makes sure that the received data is not de-queued and can be read/processed by proper receive routine). This is the method used by Ulimiate TCP/IP.


这篇关于如何检查套接字连接是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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