Check if socket is connected or not(检查socket是否连接)
问题描述
我有一个应用程序需要在某个时间向服务器发送一些数据.简单的方法是关闭连接,然后在我想发送一些东西时再次打开它.但是我想保持连接打开,所以当我想发送数据时,我首先使用这个函数检查连接:
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是否连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查socket是否连接
基础教程推荐
- 使用scanf()读取字符串 1970-01-01
- C++按值调用 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- 初始化变量和赋值运算符 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- C语言访问数组元素 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- C++定义类对象 1970-01-01
- C++ #define 1970-01-01