检查套接字连接或不 [英] Check if socket is connected or not

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

问题描述

我有需要在一定的时间的一些数据发送到服务器的应用程序。最简单的方法是关闭的连接,然后再次打开它时,我想送点东西。但我要保持连接打开,所以当我要发送数据时,我第一次使用此功能检查连接:

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);

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

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