我目前正在尝试了解Python中的套接字,并且我使用以下代码从热点网络上的智能手机接收通过TCP传输的数据。
import socket
import logging
# Logging routine
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 5000)
logger.info('starting up on %s port %s' % server_address)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
# Wait for a connection
logger.info('waiting for a connection')
connection, client_address = sock.accept()
try:
logger.info('connection from', client_address)
while True:
data = connection.recv(16)
if data:
print 'Do stuff here'
else:
print 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
我第一次运行代码时一切正常。运行脚本并想再次运行后,我出现以下错误:[Errno 48] Address already in use?
。但是,如果我在程序崩溃后再次运行脚本,则一切正常。我已检查并确认它以connection.close()
的finally语句结束。似乎我总是运行程序两次才能连续运行两次。
答案 0 :(得分:2)
这是因为上一次执行使套接字处于TIME_WAIT
状态,无法立即重用。
为了防止这种情况,请设置socket.SO_REUSEADDR
:
更改
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
到
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR, 1)