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%,我还没成功过...
相关推荐
ManThink Technology1 小时前
如何使用EBHelper 简化EdgeBus的代码编写?
java·前端·网络
珠海西格电力科技2 小时前
微电网能量平衡理论的实现条件在不同场景下有哪些差异?
运维·服务器·网络·人工智能·云计算·智慧城市
QT.qtqtqtqtqt2 小时前
未授权访问漏洞
网络·安全·web安全
半壶清水2 小时前
[软考网规考点笔记]-软件开发、项目管理与知识产权核心知识与真题解析
网络·笔记·压力测试
JMchen1233 小时前
Android后台服务与网络保活:WorkManager的实战应用
android·java·网络·kotlin·php·android-studio
yuanmenghao3 小时前
Linux 性能实战 | 第 7 篇 CPU 核心负载与调度器概念
linux·网络·性能优化·unix
那就回到过去3 小时前
MPLS多协议标签交换
网络·网络协议·hcip·mpls·ensp
那就回到过去4 小时前
VRRP协议
网络·华为·智能路由器·ensp·vrrp协议·网络hcip
极客小云4 小时前
【ComfyUI API 自动化利器:comfyui_xy Python 库使用详解】
网络·python·自动化·comfyui
符哥20084 小时前
用Apollo + RxSwift + RxCocoa搭建一套网络请求框架
网络·ios·rxswift