当对等点 1 连接到对等点 2 时
- 图片中突出显示的代码应该触发
- 对等点 2 应向对等点 1 发送“你好!”
- 对等点 1 应该有“hello!”在其控制台中打印
对等点 1 连接到对等点 2
问题: 对等点 1 没有“hello!”在其控制台中打印
// 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!');
});
最佳答案
实际上,连接本身可能存在问题。
完成此操作后
const peer = new Peer('', {
host: '/',
port: '3001'
});
创建并返回一个新的对等对象,但是套接字需要一些时间才能打开。 如果将调试设置为 3,则可以检查此项,
如果在打开套接字之前调用 connect 函数,connect
将失败
const conn = peer.connect('another-peers-id');
您可以尝试为 connect
添加一个 setTimeout
来测试这个理论。
setTimeout(() => {
const conn = peer.connect('id');
}, 1000);
'connection'
回调也存在同样的问题
您也可以在连接回调中添加 setTimeout
peer.on("connection", (conn) => {
console.log("Connected to: " + conn.peer);
setTimeout(() => {
...enter code here...
}
)
关于javascript - PeerJS - connection.on ('open' )未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65673692/