当前位置:网站首页>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
边栏推荐
- 拼接hql时,新增字段没有出现在构造方法中
- Use of ansible and common modules
- Usage of BC
- 金九银十,入职字节跳动那一天,我哭了(蘑菇街被裁,奋战7个月拿下offer)
- 初始c语言大致框架适合复习和初步认识
- Swift - Literal,字面量协议,基本数据类型、dictionary/array之间的转换
- Design of single chip microcomputer Proteus for temperature and humidity monitoring and alarm system of SHT11 sensor (with simulation + paper + program, etc.)
- ASEMI超快恢复二极管与肖特基二极管可以互换吗
- 8.2 文本预处理
- Matrix exchange row and column
猜你喜欢

51 MCU + LCD12864 LCD Tetris game, proteus simulation, ad schematic diagram, code, thesis, etc

流程控制之分支语句

TLC5615 based multi-channel adjustable CNC DC regulated power supply, 51 single chip microcomputer, including proteus simulation and C code

8.4 循环神经网络从零实现

AT89C52单片机的频率计(1HZ~20MHZ)设计,LCD1602显示,含仿真、原理图、PCB与代码等

Swift Protocol 关联对象 资源名称管理 多线程GCD 延迟 once

本以为能躺着进华为,结果陆续收到京东/滴滴/爱奇艺offer的我迷茫了

1分钟看懂执行流程,永久掌握for循环(附for循环案例)

Outsourcing for four years, abandoned

Matlab Simulink modeling and design of single-phase AC-AC frequency converter, with MATLAB simulation, PPT and papers
随机推荐
线程同步、生命周期
c语言在结构体传参时参数压栈问题
A blog allows you to learn how to write markdown on vscode
外包干了四年,废了...
Want to be an architect? Tamping the foundation is the most important
Detailed explanation of SAR command
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)
MySQL报错packet out of order
如何打开Win10启动文件夹?
we引用My97DatePicker 实现时间插件使用
矩阵交换行列
如何5分钟上手使用OCR
8.2 文本预处理
Upgrade of openssh and modification of version number
C语言p2选择分支语句详解
电容
一个月把字节,腾讯,阿里都面了,写点面经总结……
epoll 的 ET,LT工作模式———实例程序
成都控制板设计提供_算是详细了_单片机程序头文件的定义、编写及引用介绍
C语言知识点精细详解——初识C语言【1】——你不能不知的VS2022调试技巧及代码实操【2】