我正在学习这个关于套接字的教程,我做得很好,直到老师在34分44秒时再次在文本编辑器中运行该程序。在我这边,我收到一条错误消息,说socket.error:[Erno 48]地址已在使用。我使用的是Macbook,我的文本编辑器是Atom。如果能得到任何帮助来修复或解决此错误,我将不胜感激!
回溯
Traceback (most recent call last):
File "/Users/lyons/Documents/sockets/server.py", line 16, in <module>
server.bind(ADDR)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 48] Address already in use
[Finished in 0.393s]
服务器.py
import socket
import threading
HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print("[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
print("[{}] {}".format(addr, msg))
conn.close()
def start():
server.listen()
print("[LISTENING] Server is listening on {}".format(SERVER))
while True:
conn, addr = server.accept() # BLOCKING LINE OF CODE
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print("[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
客户端.py
import socket
HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
一个明显的原因是您已经有一个服务器实例在运行。
一个更棘手的情况是当一个连接在";脏的";方法这个";隔离;地址一段时间后才能再次使用。您可以通过在套接字上设置SO_REUSEADDR标志来解决此问题。
编辑:这里有更多的阅读,虽然不是在SO.上