Linux 作为服务器系统, 当 socket 运行高并发 TCP 程序时, 通常会出现连接建立到一定个数后不能再建立连接的情况
本人在工作时, 测试高并发 tcp 程序(GPS 服务器端程序), 多次测试, 发现每次连接建立到 1000 左右时, 再也不能建立 tcp 连接, 最总上网搜索, Linux 系统默认 ulimit 为 1024 个访问 用户最多可开启的程序数目. 一般一个端口的最高连接为 2 的 16 次方 65535
第一步, 修改 / etc/security/limits.conf 文件, 在文件中添加如下行(* 指代系统用户名), 修改 Linux 系统对用户的关于打开文件数的软限制和硬限制:
- soft nofile 65535
- hard nofile 65535
第二步, 修改 / etc/pam.d/login 文件, 在文件中添加如下行:
session required /lib/security/pam_limits.so
如果是 64bit 系统的话, 应该为 :
session required /lib64/security/pam_limits.so
第三步, 修改 / etc/sysctl.conf 文件, 在文件中 (清楚文件原始内容) 添加如下行(修改网络内核对 TCP 连接的有关限制):
- net.ipv4.ip_local_port_range = 1024 65535
- net.core.rmem_max=16777216
- net.core.wmem_max=16777216
- net.ipv4.tcp_rmem=4096 87380 16777216
- net.ipv4.tcp_wmem=4096 65536 16777216
- net.ipv4.tcp_fin_timeout = 10
- net.ipv4.tcp_tw_recycle = 1
- net.ipv4.tcp_timestamps = 0
- net.ipv4.tcp_window_scaling = 0
- net.ipv4.tcp_sack = 0
- net.core.netdev_max_backlog = 30000
- net.ipv4.tcp_no_metrics_save=1
- net.core.somaxconn = 262144
- net.ipv4.tcp_syncookies = 0
- net.ipv4.tcp_max_orphans = 262144
- net.ipv4.tcp_max_syn_backlog = 262144
- net.ipv4.tcp_synack_retries = 2
- net.ipv4.tcp_syn_retries = 2
第四步, 执行如下命令(使上述设置生效):
- /sbin/sysctl -p /etc/sysctl.conf
- /sbin/sysctl -w.NET.ipv4.route.flush=1
第五步, 执行如下命令(Linux 系统优化完网络必须调高系统允许打开的文件数才能支持大的并发, 默认 1024 是远远不够的):
- echo ulimit -HSn 65536>> /etc/rc.local
- echo ulimit -HSn 65536>>/root/.bash_profile
- ulimit -HSn 65536
来源: http://www.bubuko.com/infodetail-2787205.html