我创建了一个服务器程序和一个客户端程序,其目的是让客户端发送服务器TCP数据包。在我的情况下,为客户端提供了服务器的IP地址以及应将数据包发送到的端口。如果我是第一次为特定端口运行服务器代码,则服务器程序将搜索响应。如果我运行两次或两次以上,则会出现错误“地址已在使用中”。似乎套接字未正确关闭。
如我的代码所示,我在程序结尾尝试了sock.shutdown()和sock.close()无济于事。我也尝试添加connection.close()和sock.setsockopt(),但是,我相信我可能会将Python 2与Python 3语法混淆了。 (我正在使用Python 3)添加或删除这些方法会导致相同的错误。我已经在下面发布了服务器代码以供参考。
import socket
# TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('10.0.2.6', 2104)
print('Starting up {} port {}'.format(*server_address))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allows address to be reused
sock.bind(server_address)
# Listen for incoming connections, looking for one connection.
sock.listen(1) # The number of queried connections.
while True:
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
# Receive the data in small chunks and then send back
while True:
data = connection.recv(90)
print('received {!r}'.format(data))
if data:
print('sending data back to the client')
connection.sendall(data)
break
else:
print('no data from', client_address)
break
finally:
print("Closing current connection") # Cleans up the connection
connection.close()
sock.shutdown(socket.SOCK_STREAM, socket.AF_NET)
sock.shutdown(1)
sock.close()
我希望程序继续执行同一部分的多次执行。但是,运行这段代码一次给了我错误
socket.error: [Errno 98] Address already in use.