当前位置:网站首页>如何在关闭socket连接的时候跳过TIME_WAIT的等待状态
如何在关闭socket连接的时候跳过TIME_WAIT的等待状态
2022-06-29 02:40:00 【Hello,C++!】
原因分析:
socket关闭之后并不会立即收回,而是要经历一个TIME_WAIT的阶段。windows下最多可以达到4分钟。在这个时候对这个端口进行重新绑定就会出错。
方式一:
设置 SO_REUSEADDR
if ((fd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
return -1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0) {
close(fd);
return -1;
}
方式二:
在closesocket的时候,使用setsockopt设置SO_DONTLINGER。
int z; /* Status code*/
int s; /* Socket s */
struct linger so_linger;
...
so_linger.l_onoff = TRUE;
so_linger.l_linger = 30; // 30秒的超时时限
z = setsockopt(s,
SOL_SOCKET,
SO_LINGER,
&so_linger,
sizeof so_linger);
if ( z )
perror("setsockopt(2)");
这l两种方式可以跳过TIME_WAIT的阶段,客户端重启后可以快速进行连接。通常使用这个设置来加强网络程序的健壮性。
边栏推荐
猜你喜欢

Overview of PMP project management

干货丨微服务架构是什么?有哪些优点和不足?

PWN attack and defense world guess_ num

Day10 enumeration class and annotation

音响是如何把微弱声音放大呢

Understanding and design of high concurrency

對補wasm環境的一些測試

What is the dry goods microservice architecture? What are the advantages and disadvantages?

微信小程序自定义组件

Mipi d-phy -- contents of HS and LP agreements
随机推荐
PMP商业分析概述
PHP的system函数
Today's sleep quality record 82 points
OpenResty 使用介绍
【一起上水硕系列】最简单的字幕配置
They all talk about interviews with big factories. When I interview with small factories, I invite people to drink tea?
Learning Tai Chi Maker - mqtt Chapter II (IX) test of this chapter
ArrayList basic operation and add element source code
Troubleshooting of pyinstaller failed to pack pikepdf
SQL training 01
What is a thread pool?
温度转换 II
Handling method of occasional error reporting on overseas equipment
Calculate rectangular area
Introduction to openresty
EMC、EMI、EMS的關系
【无标题】
chrome浏览器关闭更新弹窗
[線性代數] 1.1 二階與三階行列式
PMP Business Analysis Overview