首页
Node.js p2p 穿透

Node.js p2p 穿透

2020-11-04 15:37:22
539
0

P2P 穿透

P2P即是点到点,也叫端对端,是二点之间的直接通信。P2P穿透就是可以在复杂的网络环境下,可以在二点之间进行直接通信连接,数据通信无需经过第三方的转发或代理服务!

P2P 服务端

const dgram = require('dgram');
const server = dgram.createSocket('udp4');

server.on('close',()=>{
    console.log('socket已关闭');
});

server.on('error',(err)=>{
    console.log(err);
});

server.on('listening',()=>{
    console.log('socket正在监听中...');
});

server.on('message',(msg,rinfo)=>{
    console.log(`receive message from ${rinfo.address}:${rinfo.port}`);
    server.send('exit',rinfo.port,rinfo.address)
});

server.bind('8060');

P2P 客户端1

const dgram = require('dgram');
var client = dgram.createSocket('udp4');
client.on('close', () => {
    console.log('socket已关闭');
});
client.on('listening', () => {
    console.log('监听中')
});
client.on('error', (err) => {
    console.log(err);
});
client.on('message', function (msg, info) {
    console.log(`from:${info.port} ${info.address} msg:${msg}`)
});
client.bind(8889);

client.send('你好,我是客户端1', 19225, '116.7.99.29')

P2P 客户端2

const dgram = require('dgram');
var client = dgram.createSocket('udp4');
client.on('close', () => {
    console.log('socket已关闭');
});
client.on('listening', () => {
    console.log('监听中')
});
client.on('error', (err) => {
    console.log(err);
});
client.on('message', function (msg, info) {
    console.log(`from:${info.port} ${info.address} msg:${msg}`)
});
client.bind(8888);

client.send('你好,我是客户端2', 18912, '116.7.99.29')
评论(0)