javascript - PeerJS - connection.on('open')未执行
问题描述
当对等体 1 连接到对等体 2 时
- 图片中突出显示的代码应该触发
- 对等体 2 应该向对等体 1 发送“你好!”
- 对等点 1 应该有“你好!” 打印在其控制台中
对等体 1 连接到对等体 2
问题: 对等点 1 没有“你好!” 打印在其控制台中
// make a new peer
const peer = new Peer('', {
host: '/',
port: '3001'
});
// "connection" event fires when someone tries to connect to us
peer.on('connection', (conn) => {
console.log('someone connected');
// "data" event fires when someone sends us a message
conn.on('data', (data) => {
console.log(data);
});
// ===========================================================================
// Problem: Both Attempt 1 and Attempt 2 fail to run
// ATTEMPT 1: "open" event fires when the connection is opened
conn.on('open', () => {
conn.send('hello!');
});
// ATTEMPT 2:
conn.send('hello!');
// ===========================================================================
});
// connect to a peer
const conn = peer.connect('another-peers-id');
// after connecting to peer, send "hi" to them
conn.on('open', () => {
conn.send('hi!');
});
解决方案
你必须为你设置一个服务器端 PeerJS
运行免费的云托管版本的 PeerServer 进行测试,只需更改
const peer = new Peer('', {
host: '/',
port: '3001'
});
至
var MyPeerId ;
const peer = new Peer();
并获得一个 id 使用:
peer.on('open', function(){
MyPeerId = peer.id;
});
//this is an async function so you have be sure that you got an id before connection to someone else
//rest of your code here
function Connect(OtherPeerId){
if(!MyPeerId)
return 0; // you didn't get a peerid yet
//rest of your code
}
推荐阅读
- azure - 通过 CLI 在应用服务中启用运行状况检查
- python - 通过使用 python 中的 sys 库在终端中将文件位置和文件名作为参数传递来保存 matplotlib 图
- java - JVM 代码缓存超过 ReservedCodeCacheSize
- r - 删除R中多个变量中的字符串
- asp.net-core-webapi - 如何从 HttpContent 检索 JSON 数据
- postgresql - Postgres NOT IN 无法按预期工作
- angular - Angular dom-to-image 如何连续加载图像?
- highcharts - 防止 Highchart.js 切割 xAxis 标签
- python - 如果进程已经在运行,Python-Flask 设置队列
- r - 如何使用 AnnotationHub 或 R 中的类似方法注释与参考基因组的基因相关的感兴趣的基因组区域?