【问题标题】:Is there a way to run a python chat server from my computer so the clients can join from their computers via another network?有没有办法从我的计算机上运行 python 聊天服务器,以便客户可以通过另一个网络从他们的计算机加入?
【发布时间】: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


    【解决方案1】:

    最简单的方法是您的服务器可以申请WLAN中的公共IP,而不是某些路由器或NAT设备后面的私有内部IP。如果这里是公共的中继服务器,它也可以工作。

    如果你不能,那么你需要做 NAT traverse 来打一个洞,这样外部客户端就可以与路由器后面的服务器取得联系。为此,您可以 google 并使用 TURN/STUN/ICE。

    【讨论】:

      猜你喜欢
      • 2014-04-16
      • 2013-11-04
      • 2011-09-12
      • 2019-09-17
      • 2012-01-15
      • 2019-11-11
      • 2014-12-20
      • 2020-07-06
      • 1970-01-01
      相关资源
      最近更新 更多