一、状态变迁图
二、time_wait状态
针对time_wait和close_wait有个简单的描述帮助理解:
Due to the way TCP/IP works, connections can not be closed immediately. Packets may arrive out of order or be retransmitted after the connection has been closed. CLOSE_WAIT indicates that the remote endpoint (other side of the connection) has closed the connection. TIME_WAIT indicates that local endpoint (this side) has closed the connection. The connection is being kept around so that any delayed packets can be matched to the connection and handled appropriately. The connections will be removed when they time out within four minutes. See http://en.wikipedia.org/wiki/Transmission_Control_Protocol for more details.
发起socket主动关闭的一方 socket将进入TIME_WAIT状态,TIME_WAIT状态将持续2个MSL(Max Segment Lifetime),在Windows下默认为4分钟,即240秒,TIME_WAIT状态下的socket不能被回收使用. 具体现象是对于一个处理大量短连接的服务器,如果是由服务器主动关闭客户端的连接,将导致服务器端存在大量的处于TIME_WAIT状态的socket, 甚至比处于Established状态下的socket多的多,严重影响服务器的处理能力,甚至耗尽可用的socket,停止服务. TIME_WAIT是TCP协议用以保证被重新分配的socket不会受到之前残留的延迟重发报文影响的机制,是必要的逻辑保证.
三、windows下调整TIME_WAIT下等待的时间
On Windows platforms, the default timeout is 120 seconds, and the maximum number of ports is approximately 4,000
To avoid port exhaustion and support high connection rates, reduce the TIME_WAIT value and increase the port range.
Note: This problem does not usually appear on UNIX systems due to the higher default connection rate in those operating systems.
To set TcpTimedWaitDelay (TIME_WAIT):
Use the regedit command to access the
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\ Services\TCPIP\Parameters
registry subkey.Create a new
REG_DWORD
value named TcpTimedWaitDelay.Set the value to 60.
Stop and restart the system.
To set MaxUserPort (ephemeral port range):
Use the
regedit
command to access theHKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\ Services\TCPIP\Parameters
registry subkey.Create a new
REG_DWORD
value named MaxUserPort.Set this value to 32768.
Stop and restart the system.
四、linux中进行时长调整
参考了:
http://blog.51cto.com/kerry/105233
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 30
然后执行 /sbin/sysctl -p
让参数生效。