1

我正在尝试编写一个 UDP 聊天系统,但由于某种原因,listen() 循环不起作用,我不知道为什么。

import socket                                                                                                                                
import json
import landerdb
import threading
class PeerChat:
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.db = landerdb.Connect("nodes")
        self.brok_ip = ""
        self.brok_port = 5000

    def listen(self):
        while True:
            msg = self.sock.recv(1024)
            print msg

    def main(self):
        while True:
            msg = raw_input("> ")
            for x in self.db.find("nodes", "all"):
                self.sock.sendto(msg, tuple(x['addr']))

    def GetNodes(self):
        self.sock.sendto("as", (self.brok_ip, self.brok_port))
        with open("nodes", 'wb') as file:
            msg, addr = self.sock.recvfrom(1024)
            print msg
            file.write(msg)

if __name__ == "__main__":
    PeerChat().GetNodes()
    threading.Thread(target=PeerChat().listen).start()
    PeerChat().main()
4

0 回答 0