有关使用UDP套接字进行Python群聊的问题

时间:2019-03-19 23:33:02

标签: python sockets networking udp

这是我的python客户端脚本。它的工作方式是,每个客户端都与主机服务器(在我的情况下为AWS服务器)建立TCP连接,然后服务器为它们提供所需的地址,以便客户端可以通过UDP直接彼此通信。

但是当我使用2个不同IP上的2个客户端进行测试时,没有收到消息。另外,如果我从机器A发送“这是A”,从机器B发送“这是B”,我将在A上看到2条收到的消息,分别是“从A:这是A”和“从B:这是A”。 (打印内容在receiveHandler函数中)这告诉我我的套接字有问题。在这种情况下,机器B根本不打印任何消息,这很奇怪。

感谢您的帮助,谢谢。为了防万一,我将放置服务器脚本。

import socket
import threading

class Client:
    socket_peers = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    socket_server = socket.socket()
    peers = []

    def __init__(self, SERVER):
        self.server = SERVER
        self.socket_server.connect(SERVER)
        self.socket_peers.bind(("0.0.0.0", 5000))

    def serverHandler(self):
        while True:
            serverData = self.socket_server.recv(1024)
            serverData = serverData.decode()
            if serverData[0] == "$": # alert message
                print(serverData[1:])
            if serverData[0] == "@": # new peer
                new_peer = (serverData[1:], 5000)
                self.peers.append(new_peer)
            if serverData[0] == "^": # quit
                break

    def sendingHandler(self):
        while True:
            message = str(input(">>"))
            for peer in self.peers:
                self.socket_peers.sendto(message.encode(), peer)

    def receiveHandler(self):
        while True:
            data, addr = self.socket_peers.recvfrom(1024)
            print("From " + str(addr) + ": " + data.decode())

    def run(self):
        serverThread = threading.Thread(target=self.serverHandler)
        sendingThread = threading.Thread(target=self.sendingHandler)
        receiveThread = threading.Thread(target=self.receiveHandler)

        serverThread.start()
        sendingThread.start()
        receiveThread.start()

        serverThread.join()
        sendingThread.join()
        receiveThread.join()

        print("Goodbye.")

    def shutdown(self):
        self.socket_server.close()
        self.socket_peers.close()

if __name__ == '__main__':
    host = "123.456.789.0" # This is where I put my AWS server public IP
    port = 5000
    hostServer = (host, port)
    client = Client(hostServer)
    client.run()
    client.shutdown()

这是在我的AWS实例上运行的服务器脚本。

import socket

class Server:
    sock = socket.socket()
    clients = []
    shutdown = False

    def __init__(self):
        self.sock.bind(("0.0.0.0", 5000))

    def run(self):
        self.sock.listen(100)
        print "Listening for connections... "

        while not self.shutdown:
            conn, addr = self.sock.accept()
            self.clients.append((conn, addr))
            self.broadcastNewPeer(addr)
            self.broadcastAlert("User: " + str(addr[0]) + " has joined.")
            print str(addr[0])

    def broadcastAlert(self, message):
        alert = "$" + message
        for client in self.clients:
            client[0].send(alert.encode())

    def broadcastNewPeer(self, addr):
        peerMsg = "@" + str(addr[0])
        for client in self.clients:
            client[0].send(peerMsg.encode())

    def broadcastForceQuit(self):
        quitMsg = "^"
        for client in self.clients:
            client[0].send(quitMsg.encode())

    def close(self):
        self.shutdown = True
        self.broadcastForceQuit()
        for client in self.clients:
            client[0].close()
        self.sock.close()

if __name__ == '__main__':
    myServer = Server()
    myServer.run()
    print "Goodbye."

0 个答案:

没有答案