【发布时间】:2021-05-14 08:37:17
【问题描述】:
我用python andsocket写了一个聊天服务器。客户端可以通过本地网络连接到它,但我需要客户端能够从另一个网络连接到服务器。我尝试使用 0.0.0.0 作为服务器中的主机 IP,但在尝试通过另一个网络连接到它时收到此错误消息
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
这是我的服务器代码
import threading
import socket
host = "0.0.0.0"
port = 55555
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()
clients = []
usernames = []
print("Server is online and running......")
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
user = usernames[index]
broadcast(f"{user} left the chat!".encode("ascii"))
usernames.remove(user)
break
def receive():
while True:
client, address = server.accept()
print(f"Connected With {str(address)}")
client.send("NICK".encode("ascii"))
username = client.recv(1024).decode("ascii")
usernames.append(username)
clients.append(client)
print(f"Username - {username}")
broadcast(f"{username} just Joined the chat!".encode("ascii"))
client.send("connected to the server!".encode("ascii"))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
这是客户端的代码
import socket
import threading
username = input("Your username : ")
host = "172.28.0.2"
port = 12344
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))
def receive():
while True:
try:
message = client.recv(1024).decode("ascii")
if message == "NICK":
client.send(username.encode("ascii"))
else:
print(message)
except:
print("An error occurred!")
client.close()
break
def write():
while True:
message = f"{username}: {input('')}"
client.send(message.encode("ascii"))
receive_thread = threading.Thread(target=receive)
receive_thread.start()
write_thread = threading.Thread(target=write)
write_thread.start()
基本上,我需要客户端能够在没有本地网络的情况下从他们的计算机连接到我的计算机上运行的服务器。
【问题讨论】:
标签: python multithreading sockets chat