当前位置:网站首页>One of the advanced applications of I / O reuse: non blocking connect -- implemented using select (or poll)
One of the advanced applications of I / O reuse: non blocking connect -- implemented using select (or poll)
2022-04-23 14:40:00 【m0_ fifty-one million five hundred and fifty-one thousand three】
One 、 What is Non blocking connect
?
The only non blocking we've used before socket The file descriptor is in Server , Using non blocking methods can greatly improve the efficiency of server programs .
Now imagine , We put Client program socket Set to non blocking , So what should I do socket File descriptors connect
The connection is easy to report errors . Why? ? because , Non blocking , The call to the file descriptor directly returns the result , and socket It's hard to connect so fast , So it's easy to call and fail , This will set errno
The value of is :EINPROGRESS
. This error type occurs in , For non blocking socket call connect
, When the connection is not established . So when connect
return -1 when , It doesn't have to be a mistake , Maybe the connection is still in progress !
The solution to this matter is , call select
、poll
Wait for the function to listen for the connection failure socket Writable events on . When select
or poll
When the function returns , recycling getsockopt
Read the error code . If the error code is 0, Just now connect There was no mistake , Connection established successfully , If the error code is 1, Indicates that an error has indeed occurred .
So troublesome to use non blocking connect
Is there any benefit ?
By using non blocking connect
, We will Can initiate multiple connections at the same time and wait together .
2、 Non blocking connect
Example program
The following is a client program , It uses a non blocking socket Connect to server .
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<stdio.h>
#include<assert.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<time.h>
#include<sys/ioctl.h>
#define BUFFER_SIZE 1023
int setnonblocking(int fd)
{
int old_option = fcntl(fd, F_GETFL);
int new_option = old_option | O_NONBLOCK;
fcntl(fd, F_SETFL, new_option);
return old_option;
}
/* Timeout connection function , The parameters are IP Address , Port number , And overtime ( millisecond ). Successful return of connection status socket, Failure to return -1 */
int unblock_connect(const char* ip, int port, int time)
{
int ret = 0;
struct sockaddr_in address;
bzero(&address, sizeof(address));
address.sin_family = AF_INET;
address.sin_port = htons(port);
inet_pton(AF_INET, ip, &address);
int sockfd = socket(PF_INET, SOCK_STREAM, 0);
int fdopt = setnonblocking(sockfd);
ret = connect(sockfd, (struct sockaddr*)&address, sizeof(address));
if (ret == 0) /* The connection is successful */
{
/* If the connection is successful , Then recover sockfd Properties of , And return immediately */
printf("connect whit server immediately\n");
fcntl(sockfd, F_SETFL, fdopt);
return sockfd;
}
else if (errno != EINPROGRESS) /* If the error type is not EINPROGRESS, Indicates that other errors have occurred , Return immediately */
{
/* If the connection is not established immediately , Then only when errno yes EINPROGRESS The connection is still in progress , Otherwise, an error is returned */
printf("unblock connect not support\n");
return -1;
}
fd_set readfds;
fd_set writefds;
struct timeval timeout;
FD_ZERO(&readfds);
FD_SET(sockfd, &writefds);
timeout.tv_sec = time;
timeout.tv_usec = 0;
ret = select(sockfd + 1, NULL, &writefds, NULL, &timeout);
if (ret <= 0)
{
/* select Timeout or error , Return immediately */
printf("connection time out\n");
close(sockfd);
return -1;
}
if (!FD_ISSET(sockfd, &writefds)) /* If sockfd Don't write , Indicates that the connection failed , Return immediately */
{
printf("no events on sockfd found\n");
close(sockfd);
return -1;
}
int error = 0;
socklen_t length = sizeof(error);
/* call getsockopt To get and clear sockfd Mistakes on */
if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &length) < 0)
{
printf("connection failed after select with the error: %d\n", error);
close(sockfd);
return -1;
}
/* Error number is not 0 Indicates a connection error */
if (error != 0)
{
printf("connection failed after select with the error: %d\n", error);
close(sockfd);
return -1;
}
/* Successful connection */
printf("connection ready after select with the socket: %d\n", sockfd);
fcntl(sockfd, F_SETFL, fdopt);
return sockfd;
}
int main(int argc, char* argv[])
{
if (argc <= 2)
{
return 1;
}
const char* ip = argv[1];
int port = atoi(argv[2]);
int sockfd = unblock_connect(ip, port, 10);
if (sockfd < 0)
{
return 1;
}
close(sockfd);
return 0;
}
版权声明
本文为[m0_ fifty-one million five hundred and fifty-one thousand three]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231435333788.html
边栏推荐
- 单片机的函数信号发生器,输出4种波形,频率可调,原理图,仿真和C程序
- capacitance
- 51 MCU flowers, farmland automatic irrigation system development, proteus simulation, schematic diagram and C code
- OC 转 Swift 条件编译、标记、宏、 Log、 版本检测、过期提示
- Matrix exchange row and column
- MDS55-16-ASEMI整流模块MDS55-16
- I thought I could lie down and enter Huawei, but I was confused when I received JD / didi / iqiyi offers one after another
- QT interface optimization: QT border removal and form rounding
- UML project example -- UML diagram description of tiktok
- Want to be an architect? Tamping the foundation is the most important
猜你喜欢
PWM speed regulation control system of DC motor based on 51 single chip microcomputer (with complete set of data such as Proteus simulation + C program)
四层和八层电梯控制系统Proteus仿真设计,51单片机,附仿真和Keil C代码
we引用My97DatePicker 实现时间插件使用
51 Single Chip Microcomputer Design of traffic light system (with Proteus simulation, C program, schematic diagram, PCB, thesis and other complete data)
查找水仙花数-for循环实践
Parameter stack pressing problem of C language in structure parameter transmission
555定时器+74系列芯片搭建八路抢答器,30s倒计时,附Proteus仿真等
本以为能躺着进华为,结果陆续收到京东/滴滴/爱奇艺offer的我迷茫了
基于TLC5615的多路可调数控直流稳压电源,51单片机,含Proteus仿真和C代码等
循环队列的基本操作,你学会了吗?
随机推荐
压缩映射定理
Nacos uses demo as configuration center (IV)
想要成为架构师?夯实基础最重要
Swift:Entry of program、Swift调用OC、@_silgen_name 、 OC 调用Swift、dynamic、String、Substring
抑郁症治疗的进展
Detailed explanation of SAR command
1N5408-ASEMI整流二极管1N5408
The initial C language framework is suitable for review and preliminary understanding
详解TCP的三次握手
Design of single chip microcomputer Proteus for temperature and humidity monitoring and alarm system of SHT11 sensor (with simulation + paper + program, etc.)
UML project example -- UML diagram description of tiktok
金九银十,入职字节跳动那一天,我哭了(蘑菇街被裁,奋战7个月拿下offer)
Swift Protocol 关联对象 资源名称管理 多线程GCD 延迟 once
51单片机+LCD12864液晶显示的俄罗斯方块游戏,Proteus仿真、AD原理图、代码、论文等
帧同步 实现
流程控制之分支语句
Arduino for esp8266串口功能简介
Electronic perpetual calendar of DS1302_ 51 single chip microcomputer, month, day, week, hour, minute and second, lunar calendar and temperature, with alarm clock and complete set of data
Qt界面优化:Qt去边框与窗体圆角化
你還不知道責任鏈模式的使用場景嗎?