【go-libp2p学习笔记】使用go-libp2p搭建中转服务器(circuit relay server)

使用Go语言编写区块链P2P网络(译) 外文发表日期: 2018-04-14 外文链接:https://medium.com/coinmonks/code-a-simple-p2p-blockchain-in-go-46662601f417 在之前的文章中,我们已经知道了怎么编写PoW也知道了IPFS怎么工作, 但是有一个致命的缺点,我们的服务都是中心化的,这篇文章会教你怎么实现一个简单的完全去中心化的P2P网络。 ... 阅读详情
AI摘要

本文介绍如何使用Go-libp2p库搭建NAT穿透的中转服务器(circuit relay server),实现两个处于NAT后的节点通过该服务器建立P2P连接。文章详细解释了libp2p的基本概念,如libp2p节点、Multiaddr等,并提供了一个具体的代码实例,展示了客户端和服务端的核心代码。

使用go-libp2p搭建中转服务器(circuit relay server)

libp2p算是一个蛮新的库,提供了非常强大的p2p节点发现/连接/通信能力。IPFS的基石。
中文网上的技术教程比较少,所以抛砖引玉开一点坑来体验一下!

这篇博客本质上就是用libp2p做一个NAT打洞建立p2p的实现,不过过程中能够学到很多libp2p的概念,当然用libp2p做也应该有不少好处有待进一步研究。

代码基于:
https://github.com/libp2p/go-libp2p/tree/master/examples
和一些外网教程

复现本篇博客的技术基础

  1. 基础的Go语言能力(我也不是很懂,GO能学的太多了,超过我上一篇博客的内容基本上都不会)
  2. Go version>=1.19(libp2p的要求)
  3. NAT与NAT打洞相关概念
  4. 一台具有公网IP的服务器
  5. 你自己的电脑

1. 了解一些libp2p基础概念

  1. libp2p-node, 或说Host, 中文名节点, 不是指网络中的一个主机, 而是指的网络连接中的一个独立端点, 一个独立的应用程序, 一台电脑/服务器上面可以配置多个host. 在go-libp2p的example中, 很多测试都是在同一个电脑上运行的.
  2. Multiaddr, libp2p网络传输层的协议中, 用一个Multiaddr概念来统领两个节点之间的多种连接方式. 从而对更高层的应用隐藏底部的具体连接协议.

2. 原理

两个藏在NAT或防火墙后面的host:A, B; 一个可以被公网访问到的(比如说具有公网IP)host:R
这里A是等待被访问的host, B是要去访问A的host
首先A需要先去连接中转服务器R, 进行一个预定Reservation, 这样A和R的双向通路就打开了.
接下来B向R发出连接到A的请求, R帮助B与A建立连接
20221101101037

3. 代码核心语句解释

代码主要分为两个程序: 客户端和服务端/中转服务器

中转服务器的核心代码:
	relay1, err := libp2p.New()
 	_, err = relay.New(relay1)

    log.Printf("relay1Info ID: %v Addrs: %v",relay1.ID(), relay1.Addrs())

就这么短, 很简单.
第一句话创建一个新的host,
第二句话在host上配置中转服务器
第三句话将host的ID和地址打印出来, 这里我们手动复制传给A和B

客户端的核心代码:

客户端也分为两个部分, 等待被连接的Ahost, 和去连接A的Bhost.
这里我们直接用是否输入了被连接的Ahost的ID作为本客户端是A还是B的判断条件.
等待被连接的Ahost

	unreachableNode, err := libp2p.New(
		libp2p.NoListenAddrs,
		// Usually EnableRelay() is not required as it is enabled by default
		// but NoListenAddrs overrides this, so we're adding it in explictly again.
		libp2p.EnableRelay(),
	)


    relayServerID := "12D3KooWHwN52aYe18Wa6meTcLtrQ6y7jKXaQ85zf2snxsUWPA9B"
	ms1, _ := ma.NewMultiaddr(fmt.Sprintf("/ip4/43.143.xxx.xxx/tcp/38403/p2p/%v", relayServerID))
	relay1info, err := peer.AddrInfoFromP2pAddr(ms1)
    if err := unreachableNode.Connect(context.Background(), *relay1info); err != nil {
   
   
       log.Printf("Failed to connect unreachable1 and relay1: %v", err)
       return
	}
 	_, err = client.Reserve(context.Background(), unreachableNode, *relay1info)
    

	// Now, to test the communication, let's set up a protocol handler on unreachable2
	unreachableNode.SetStreamHandler("/chatStream", func(s network.Stream) {
   
   
		log.Println("Awesome! We're now communicating via the relay!")
		log.
rock-paper-scissors-demo:使用libp2p演示剪刀石头布剪刀 剪刀石头布演示 使用libp2p演示剪刀石头布剪刀 这是在柏林Go开发人员聚会上如何快速使用libp2p的代码。 可以在这里找到幻灯片: : 安装Dep curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh 安装依赖项 dep ensure 建造 go build -o player player.go 运行-3个不同的终端 运行DHT引导节点 ./player -p 30000 -prefix dht -bootstrap 运行播放器1节点 ./player -p 30001 -prefix enc_1 运行播放器2节点 ./player -p 30002 -prefix enc_2 立即下载

相关推荐

go-libp2p-http:位于libp2p之上的HTTP

go-libp2p-http 在libp2p之上的HTTP 包p2phttp允许使用Go的标准“ http”和“ net”堆栈通过服务HTTP端点并发出HTTP请求。 p2phttp代替了常规的“ host:port”寻址, p2phttp使用Peer ID并让libp2p负责路由,从而利用了多路由,NAT穿越和通过单个连接进行流多路复用等功能。 目录 安装 该软件包是一个使用Go模块进行依赖管理的库。 用法 完整的文档可以在上阅读。 重要的部分如下。 http.Server上的简单http.Server工作方式如下: listener , _ := gostream . Liste

Go-基于DPoS算法P2P对等网络的简易区块链Go语言实现

基于DPoS算法、P2P对等网络的简易区块链Go语言实现

【ros】ROS1的安装和相关使用方法

主要学习ros相关内容

Greary的博客 2386

手把手教你给H3C MSR路由器配置4G/5G上网(保姆级图文教程)

本文提供H3C MSR路由器配置4G/5G上网的保姆级图文教程,涵盖硬件准备、运营商适配、命令行配置、多运营商策略优化及信号故障排查等全流程。通过实测数据和典型场景分析,帮助用户快速实现4G/5G模块的部署与优化,提升网络稳定性和业务连续性。

weixin_28745067的博客 446

Unity集成阿里Qwen2.5-Omni全模态大模型实战:语音交互与多模态AI开发指南

本文详细介绍了在Unity中集成阿里Qwen2.5-Omni全模态大模型的实战指南。通过C#脚本开发,实现语音交互、图像分析等多模态AI功能,涵盖API调用、音频处理、流式响应解析等核心步骤,为游戏、虚拟人等Unity应用提供沉浸式智能交互解决方案。

weixin_29005499的博客 319

避坑指南:Qwen2.5-VL图片预处理中常见的5个尺寸错误

本文深入解析了Qwen2.5-VL模型在图片预处理环节中开发者最常遇到的五个尺寸错误,包括动态分辨率对齐、宽高比超标、像素数限制等问题。文章结合源码解读,详细剖析了`process_vision_info`函数和`resize`逻辑,并提供了具体的排查流程图与参数设置建议,旨在帮助开发者构建健壮的预处理流水线,有效规避显存溢出与推理失败的风险。

weixin_29290379的博客 180

基于Simulink的直流电机双闭环调速系统抗扰动仿真与参数优化

本文详细介绍了基于Simulink的直流电机双闭环调速系统仿真与参数优化方法。通过构建转速外环与电流内环的仿真模型,阐述了利用工程设计法整定PI参数的核心步骤,并重点探讨了如何优化系统参数以增强其抗负载突变等扰动的能力,实现快速、平稳的调速性能。

weixin_29061997的博客 200

MTK AWB 色温曲线的进一步猜想

平均距离来判断是否对该色温下白平衡进行全部收白处理,还是保留一些光源的本身的颜色。比如占据图像一大半左右的纯色背景,纵坐标值相对横坐标的距离应该会比较大,大于一般场景下的正常白点分布。反之,位于Plank_curve下方位置的点具有偏洋红色的倾向。此时拟合各个色温下的白点,拟合曲线大致是以X= 0.85)平行于横轴的一条直线。对原始坐标系中的点取对数后的Log坐标系空间。此时拟合各个色温下的白点,拟合曲线大致呈现的是一条直线。,可以认为是各种色温下白点分布所呈现的走向。的算法利用某个色温点的偏离。

大熊 727

Transformer 面试题及详细答案120道(1-10)-- 基础概念

本文总结了Transformer模型的10个常见面试问题及答案,涵盖了其核心结构、创新点、工作机制等关键知识点。主要内容包括:Transformer的自注意力机制和多头注意力机制创新点,相比RNN/CNN的优势,模型在《Attention Is All You Need》论文中的提出背景,以及Encoder-Decoder协同工作流程等。重点解析了位置编码的作用、长距离依赖处理能力、与传统注意力机制的区别等核心问题。每个问题都给出了简明扼要的专业解答,适合作为Transformer相关面试准备的参考资料。

大剑师兰特的GIS世界 854

【stata基础代码大全 】 可独立完成一篇实证

用stata打开,直接替换自己需要的变量就行,小白友好❗️❗️❗️。八、八.中介效应检验:路径分析(三种方法)第二种方法即Sobel-Goodman检验。*(7)Winsor处理,剔除异常值。六、内生性问题解决方法(附具体模型)其三,工具变量:两阶段最小二乘。第三种方法即Bootstrap检验。二、Stata中数据的基本处理。*(5)生成行业、年度虚拟变量。PSM1————近邻匹配。七、调节效应检验:机制分析。*(2)剔除数据中的样本。*(4)给变量添加标签。*(3)生成新的变量。*(6)基本数据匹配。

J_Giser的博客 8029

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

上一篇: Go语言入门笔记
Cake_C
博客等级 码龄9年 267粉丝 101原创
评论 12
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值