'A confusing BUG on continiousg linking to nonblocking TCP socket when bind to port 80 (python3)?
I'm writing a multi-thread web server. I tried to bind a non-blocking tcp socket to port 80. When I tested it in two terminals, I found the server cannot recv message until the client socket was closed. (But when binding to other port, the server recv message from the client immediently).
Blow are the minimal code of this problem.
# server.py
from socket import *
import time
port = 80
so = socket() # TCP for default
so.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
so.setblocking(False)
so.bind(('', port))
so.listen()
print('Ready to server...')
while True:
try:
client_so, client_addr = so.accept()
except:
time.sleep(0.001)
else:
# now we have a connection, but ...
# Press Ctrl-C in client to see what will happend.
# And change the "port" in both file, then do the same procedure.
print(f'link to {client_addr}')
while True:
try:
msg = client_so.recv(1024).decode()
except:
time.sleep(0.001)
else:
if(msg):
print(msg)
from socket import *
import time
host = 'localhost'
port = 80
so = socket()
so.connect((host, port))
so.send('hi'.encode())
while True:
time.sleep(0.01)
- run
python server.pyin one terminal. - run
python client.pyin another terminal.
When port is 80, the server cannot recive 'hi' until client.py was stoped. But other ports do work.
I tried this both on Windows 10 and Ubuntu 20.04 (python version is 3.9.7) and get the same result.
So what happened when bind a tcp socket to port 80? Will it make some difference to behavior of the socket?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
