


TCP port occupation: Why is the port still occupied after the server program exits and how to solve it?
Python TCP server port occupation problem: The port is still occupied after the program exits and the solution
When developing a TCP server in Python, a common problem is that after the server program is closed, the target port is still in an occupied state, resulting in the inability to restart the server immediately. This article will explore this problem in depth and provide effective solutions.
Problem: Developers use socket.socket()
to create a TCP server and combine multiprocessing.pool
to process client requests. After the server terminated unexpectedly, lsof -i :6001
does not show that port 6001 is occupied, but OSError: [Errno 98] Address already in use
error occurred during restart. However, netstat -anp | grep 6001
shows a large number of connections in TIME_WAIT
state.
Cause: This is caused by the TIME_WAIT
status of the TCP connection. When the server exits abnormally, some TCP connections may not be closed correctly and enter TIME_WAIT
state. The operating system retains these ports for a period of time (mins to tens of minutes) to ensure data transmission reliability. lsof
focuses on the association between the process and the file, while the TIME_WAIT
connection is not directly held by any process, so lsof
cannot be detected; netstat
can display the network connection status, so you can see the TIME_WAIT
connection.
Solution: Set the SO_REUSEADDR
option before the server program binds the port. This option allows the port to be bound immediately when it is in the TIME_WAIT
state. The modified code is as follows:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Add serversocket.bind before bind(('0.0.0.0', port)) # ...Other codes...
Adding serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
can solve the port occupation problem caused by TIME_WAIT
status. Linux 3.9 and later kernels have added the SO_REUSEPORT
option, which is more refined than SO_REUSEADDR
. It is recommended to set these two options at the same time. Windows systems may also need to set the SO_EXCLUSIVEADDRUSE
option.
The above is the detailed content of TCP port occupation: Why is the port still occupied after the server program exits and how to solve it?. For more information, please follow other related articles on the PHP Chinese website!

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

Pythondoesnothavebuilt-inarrays;usethearraymoduleformemory-efficienthomogeneousdatastorage,whilelistsareversatileformixeddatatypes.Arraysareefficientforlargedatasetsofthesametype,whereaslistsofferflexibilityandareeasiertouseformixedorsmallerdatasets.

ThemostcommonlyusedmoduleforcreatingarraysinPythonisnumpy.1)Numpyprovidesefficienttoolsforarrayoperations,idealfornumericaldata.2)Arrayscanbecreatedusingnp.array()for1Dand2Dstructures.3)Numpyexcelsinelement-wiseoperationsandcomplexcalculationslikemea

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
