Linux下解決高並發socket最大連接數限制,tcp默認1024個連接
阿新 • • 發佈:2019-05-17
ipv4 網絡內核 linux 工作 save lib64 pro time net
linux作為服務器系統,當socket運行高並發TCP程序時,通常會出現連接建立到一定個數後不能再建立連接的情況
本人在工作時,測試高並發tcp程序(GPS服務器端程序),多次測試,發現每次連接建立到1000左右時,再也不能建立tcp連接,最總上網搜索,linux系統默認ulimit為1024個訪問 用戶最多可開啟的程序數目。一般一個端口的最高連接為2的16次方65535
- 第一步,修改/etc/security/limits.conf文件,在文件中添加如下行(*指代系統用戶名),修改Linux系統對用戶的關於打開文件數的軟限制和硬限制:
soft nofile 65535hard 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
- 第六步,重啟機器。
通過修改,tcp可以達到20000個連接完全沒有問題
Linux下解決高並發socket最大連接數限制,tcp默認1024個連接