2

我又回来了另一个 UDP Hole Punching 问题,我似乎已经弄清楚了这个概念,但我似乎仍然无法应用它。显然,要在 NAT 上打一个洞,您必须首先发送欢迎消息(或任何消息),然后发送实际数据。我正在这样做,但是当需要进行节点到节点通信时,它似乎不起作用。

这段代码是我正在开发的 P2P 聊天系统的一部分。

import socket
import threading
import json

nodes = {}

class Marboo:
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.bi = ""
        self.bp = 5002
        self.cmds = {
                "checkin":self.checkin,
                "msg":self.msg,

                }
        self.nick = "test"
        self.room = "a"
    def main(self):
        self.get_nodes()
        while True:
            data, addr = self.sock.recvfrom(102400)
            data = json.loads(data)
            print data

    def prompt(self):
        while True:
            msg = raw_input(self.nick+"> ")
            data = json.dumps({"cmd":"msg", "message":msg, "room":self.room, "nick":self.nick})
            self.send(data)

    def get_nodes(self):
        self.sock.sendto("", (self.bi, self.bp))
        data = self.sock.recv(1024)
        nodes = json.loads(data)
        for x in nodes:
            self.connect(tuple(nodes[x]))
            self.sock.sendto(json.dumps({"cmd":"checkin"}), tuple(nodes[x]))

    def send(self, msg):
        for x in nodes:
            self.connect(tuple(nodes[x]))
            self.sock.sendto(msg, tuple(nodes[x]))
    def connect(self, addr):
        self.sock.sendto(json.dumps({"cmd":"connect"}), addr)
    def checkin(self):
        pass
    def msg(self):
        pass

if __name__ == "__main__":
    threading.Thread(target=Marboo().prompt).start()
    Marboo().main()
4

0 回答 0