问题描述
我有一个应用程序需要在某个时间向服务器发送一些数据.简单的方法是关闭连接,然后在我想发送一些东西时再次打开它.但是我想保持连接打开,所以当我想发送数据时,我首先使用这个函数检查连接:
I have an application which needs to send some data to a server at some time. The easy way would be to close the connection and then open it again when I want to send something. But I want to keep the connection open so when I want to send data, I first check the connection using this function:
bool is_connected(int sock)
{
unsigned char buf;
int err = recv(sock,&buf,1,MSG_PEEK);
return err == -1 ? false : true;
}
不好的部分是这不起作用.当没有数据要接收时它会挂起.我能做什么?如何检查连接是否仍然打开?
The bad part is that this doesn't work. It hangs when there is no data to receive. What can I do? How can I check if the connection is still open?
推荐答案
不要先检查再发送.这是浪费精力并且无论如何都不会工作 - 状态可能会在您检查和发送之间发生变化.只要做你想做的事,如果失败就处理错误.
Don't check first and then send. It's wasted effort and won't work anyway -- the status can change between when you check and when you send. Just do what you want to do and handle the error if it fails.
要检查状态,请使用:
int error_code;
int error_code_size = sizeof(error_code);
getsockopt(socket_fd, SOL_SOCKET, SO_ERROR, &error_code, &error_code_size);
这篇关于检查socket是否连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!