udp穿透的方法

服务端缓存客户端ip+端口信息,如果有新的客户端连接上来返回给对方。

server

python 复制代码
import socket

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind(("0.0.0.0", 2023))
    cache = {}
    while True:
        packet = udp_socket.recvfrom(2048)
        current = packet[1]
        key = packet[0].decode("utf-8")
        print("recvfrom key:", key)
        if key not in cache:
            cache[key] = packet[1]
            print("pending:", current)
        else:
            last = cache[key]
            udp_socket.sendto((current[0] + ":" + str(current[1])).encode("utf-8"), last)
            udp_socket.sendto((last[0] + ":" + str(last[1])).encode("utf-8"), current)
            del cache[key]
            print("done:", last, current)

    udp_socket.close()


if __name__ == "__main__":
    main()

客户端先请求服务端,请求后获取p2p的地址,然后开始周期echo。

client

python 复制代码
import socket
import sys
import time

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.settimeout(10)
    server = (u"192.168.3.20",2023)
    key = u"----uni-key-yeshen----"
    this_client = sys.platform + str(time.time())

    udp_socket.sendto(key.encode("utf-8"), server)
    print("waiting..")
    packet = udp_socket.recvfrom(2048)
    print("packet",packet)
    peer = packet[0].split(":")
    target_peer = (peer[0],int(peer[1]))

    while True:
        udp_socket.sendto(this_client.encode("utf-8"), target_peer)
        print("peer send",this_client,target_peer)
        msg = udp_socket.recvfrom(2048)
        print("peer recv",msg)
        time.sleep(1)

    udp_socket.close()


if __name__ == "__main__":
    main()

自测效果:

  1. 在服务端上开启,两个客户端都在同一个局域网里面,有70%左右的概率连通(10个端口,有7个能成功)。数据和wifi都是这样。
  2. 一个设备在wifi、一个在数据上,连通的概率大约是0%,我还没成功过...
相关推荐
Smartdaili China6 小时前
掌握Java网页抓取:技术与示例完整指南
java·网络·学习·指南·网页·住宅ip·爬虫api
雾削木6 小时前
k230 Pyhton三角形识别
运维·服务器·网络·stm32·智能路由器
郝学胜-神的一滴7 小时前
Python数据模型:深入解析及其对Python生态的影响
开发语言·网络·python·程序人生·性能优化
北京聚信万通科技有限公司7 小时前
传输协议:AS3
服务器·网络·安全·电子数据交换·as3
爬山算法8 小时前
Netty(12)Netty支持哪些协议和传输方式?
网络
yong99908 小时前
基于C#与三菱FX5U PLC实现以太网通信
网络·c#·php
遇见火星8 小时前
常见Systemctl语句
linux·服务器·网络·systemctl
专家大圣9 小时前
摆脱局域网束缚!Neko+cpolar 让跨网共享成日常
服务器·网络·docker·内网穿透·cpolar
Awkwardx9 小时前
Linux网络编程—数据链路层
linux·运维·网络
揪住海10 小时前
UDP网络巩固知识基础题(1)
网络·udp