Python UDP套接字未接收数据

时间:2013-05-19 04:35:05

标签: python sockets udp nodes p2p

我正在尝试编写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()

0 个答案:

没有答案