当前位置:网站首页>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
边栏推荐
- 面试官:说一下类加载的过程以及类加载的机制(双亲委派机制)
- Four ways of SSH restricting login
- 1分钟看懂执行流程,永久掌握for循环(附for循环案例)
- Want to be an architect? Tamping the foundation is the most important
- The art of automation
- we引用My97DatePicker 实现时间插件使用
- 如何打开Win10启动文件夹?
- MQ-2和DS18B20的火灾温度-烟雾报警系统设计,51单片机,附仿真、C代码、原理图和PCB等
- raised exception class EAccexxViolation with ‘Access violation at address 45EFD5 in module 出错
- C语言知识点精细详解——初识C语言【1】——你不能不知的VS2022调试技巧及代码实操【2】
猜你喜欢
do(Local scope)、初始化器、内存冲突、Swift指针、inout、unsafepointer、unsafeBitCast、successor、
金九银十,入职字节跳动那一天,我哭了(蘑菇街被裁,奋战7个月拿下offer)
DVWA之暴力破解(Brute Force)Low-->high
AT89C51 MCU digital voltmeter development, measuring range 0 ~ 5V, proteus simulation, schematic diagram, PCB and C program, etc
Model location setting in GIS data processing -cesium
C语言知识点精细详解——初识C语言【1】——你不能不知的VS2022调试技巧及代码实操【2】
8.4 循环神经网络从零实现
ArrayList集合基本使用
A good tool: aardio
你还不知道责任链模式的使用场景吗?
随机推荐
Matrix exchange row and column
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
在游戏世界组建一支AI团队,超参数的多智能体「大乱斗」开赛
关于在vs中使用scanf不安全的问题
压缩映射定理
本以为能躺着进华为,结果陆续收到京东/滴滴/爱奇艺offer的我迷茫了
ASEMI超快恢复二极管与肖特基二极管可以互换吗
On the insecurity of using scanf in VS
单片机的函数信号发生器,输出4种波形,频率可调,原理图,仿真和C程序
四层和八层电梯控制系统Proteus仿真设计,51单片机,附仿真和Keil C代码
Interviewer: let's talk about the process of class loading and the mechanism of class loading (parental delegation mechanism)
8.5 循环神经网络简洁实现
【STC8G2K64S4】比较器介绍以及比较器掉电检测示例程序
Using MATLAB programming to realize the steepest descent method to solve unconstrained optimization problems
机器学习之逻辑回归(Logistic Regression)原理讲解和实例应用,果断收藏
外包干了四年,废了...
利用 MATLAB 编程实现最速下降法求解无约束最优化问题
QT Detailed explanation of pro file
C语言知识点精细详解——初识C语言【1】——你不能不知的VS2022调试技巧及代码实操【1】
qt之.pro文件详解