当前位置:网站首页>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
边栏推荐
- 交通灯系统51单片机设计(附Proteus仿真、C程序、原理图及PCB、论文等全套资料)
- 利用 MATLAB 编程实现最速下降法求解无约束最优化问题
- 全连接层的作用是什么?
- 压缩映射定理
- Multisim Simulation Design of DC adjustable regulated power supply of LM317 (with simulation + paper + reference)
- 【Servlet】Servlet 详解(使用+原理)
- 51 MCU + LCD12864 LCD Tetris game, proteus simulation, ad schematic diagram, code, thesis, etc
- [servlet] detailed explanation of servlet (use + principle)
- TLC5615 based multi-channel adjustable CNC DC regulated power supply, 51 single chip microcomputer, including proteus simulation and C code
- Unity_代码方式添加绑定按钮点击事件
猜你喜欢

51单片机+LCD12864液晶显示的俄罗斯方块游戏,Proteus仿真、AD原理图、代码、论文等

外包幹了四年,廢了...

阿里研发三面,面试官一套组合拳让我当场懵逼

ArrayList集合基本使用

asp.net使用MailMessage发送邮件的方法

8.3 语言模型与数据集

【Servlet】Servlet 详解(使用+原理)

如何5分钟上手使用OCR

Mq-2 and DS18B20 fire temperature smoke alarm system design, 51 single chip microcomputer, with simulation, C code, schematic diagram, PCB, etc

DS1302的电子万年历_51单片机,年月日、星期、时分秒、农历和温度,带闹钟,全套资料
随机推荐
分分钟掌握---三目运算符(三元运算符)
电子秤称重系统设计,HX711压力传感器,51单片机(Proteus仿真、C程序、原理图、论文等全套资料)
8.5 循环神经网络简洁实现
MCU function signal generator, output four kinds of waveforms, adjustable frequency, schematic diagram, simulation and C program
QT interface optimization: double click effect
1-初识Go语言
QT actual combat: Yunxi calendar
Using MATLAB programming to realize the steepest descent method to solve unconstrained optimization problems
C语言知识点精细详解——数据类型和变量【2】——整型变量与常量【1】
Raised exception class eaccexviolation with 'access violation at address 45efd5 in module error
redis的五种数据类型
AT89C52单片机的频率计(1HZ~20MHZ)设计,LCD1602显示,含仿真、原理图、PCB与代码等
SHT11传感器的温度湿度监控报警系统单片机Proteus设计(附仿真+论文+程序等)
L'externalisation a duré quatre ans.
Ali developed three sides, and the interviewer's set of combined punches made me confused on the spot
raised exception class EAccexxViolation with ‘Access violation at address 45EFD5 in module 出错
Svn detailed use tutorial
自动化的艺术
矩阵交换行列
QT interface optimization: QT border removal and form rounding