我试图使用python3中的套接字创建一个简单的聊天室。当我在本地主机上运行服务器并使用多个终端设置客户端时,一切正常。当我尝试通过连接到同一LAN网络的另一个系统连接到服务器(该服务器托管在我的系统上)时,出现此错误。
ConnectionResetError: [Errno 104] Connection reset by peer
当我尝试再次与第二个系统重新连接时,它又给了我另一个错误
BrokenPipeError: [Errno 32] Broken pipe
这是我的服务器。py
from socket import AF_INET, SOCK_STREAM, socket
from threading import Thread
HOST = "192.168.157.206"
PORT = 3000
addresses = {}
clients = {}
def Connections():
while True:
client, addr = server.accept()
print("{} is connected!!".format(addr))
client.send(("Welcome to Chat Room. Type {quit} to exit. Enter your name: ").encode("utf-8"))
addresses[client] = addr
Thread(target = ClientConnection, args=(client, )).start()
def ClientConnection(client):
name = client.recv(BufferSize).decode("utf-8")
client.send(("Hello {}".format(name)).encode("utf-8"))
message = ("{} has joined the chat..").format(name)
Broadcast(message.encode("utf-8"))
clients[client] = name
while True:
msg = client.recv(BufferSize).decode("utf-8")
if msg != "quit":
Broadcast(msg.encode("utf-8"), name + ": ")
else:
message = ("{} has left the chat.").format(clients[client])
Broadcast(message.encode("utf-8"))
client.send(("Will see you soon..").encode("utf-8"))
del clients[client]
break
def Broadcast(msg, name = ""):
for sockets in clients:
sockets.send(name.encode("utf-8") + msg)
server = socket(family=AF_INET, type=SOCK_STREAM)
try:
server.bind((HOST, PORT))
except OSError:
print("Server Busy")
BufferSize = 1024
server.listen(5)
print("Waiting for Connections... ")
AcceptThread = Thread(target=Connections)
AcceptThread.start()
AcceptThread.join()
server.close()
这是我的客户。py
from socket import AF_INET, SOCK_STREAM, socket
from threading import Thread
HOST = input("Enter Host IP: ")
PORT = eval(input("Enter Port No: "))
BufferSize = 1024
def Recieve():
while True:
try:
msg = client.recv(BufferSize).decode("utf-8")
print(msg)
except OSError:
break
def Send():
while True:
msg = input()
if msg == "quit":
client.send(msg.encode("utf-8"))
client.close()
break
else:
client.send(msg.encode("utf-8"))
client = socket(family=AF_INET, type=SOCK_STREAM)
client.connect((HOST, PORT))
RecieveThread = Thread(target=Recieve).start()
SendThread = Thread(target=Send).start()
请告诉我我哪里做错了。我经历了这个答案here。但是我无法找出在我的代码中更正此错误的位置。 预先感谢。