如何启用PeerJS连接实现数据共享?解决连接失败与消息发送问题
PeerJS 端对端聊天连接问题修复
你的代码核心问题有以下几点:
- 被动接收连接时,未将建立的连接实例赋值给全局变量,导致接收方无法使用
send/disconnect功能 send和disconnect函数未做连接实例的存在性检查,会触发未定义报错- 缺少连接错误处理,无法排查连接失败原因
- 消息接收仅用alert提示,体验不佳
修正后的完整代码
HTML
<head> <title>Messaging System</title> <script src="https://unpkg.com/peerjs@1.5.1/dist/peerjs.min.js"></script> </head> <body> <div id="peerIdDisplay"></div> <div id="messageLog"></div> <input id="targetPeerId" placeholder="对方Peer ID" /> <button onclick="connectToPeer()">连接</button> <textarea id="messageInput" placeholder="输入消息"></textarea> <button onclick="sendMessage()">发送</button> <button onclick="disconnectPeer()">断开连接</button> </body>
CSS
body { font-family: Consolas, "Courier New", Courier, monospace; max-width: 600px; margin: 20px auto; padding: 0 10px; } #messageLog { height: 200px; border: 1px solid #ccc; padding: 10px; overflow-y: auto; margin: 10px 0; } input, textarea, button { display: block; width: 100%; margin: 8px 0; padding: 8px; box-sizing: border-box; }
JavaScript
let peer = new Peer(); let activeConnection = null; // 显示自身Peer ID peer.on('open', (id) => { document.getElementById('peerIdDisplay').textContent = `我的Peer ID: ${id}`; }); // 主动发起连接 function connectToPeer() { const targetId = document.getElementById('targetPeerId').value.trim(); if (!targetId) { alert('请输入对方的Peer ID'); return; } // 关闭已有连接 if (activeConnection) { activeConnection.close(); } activeConnection = peer.connect(targetId); // 连接成功回调 activeConnection.on('open', () => { addMessageToLog(`已连接到 ${targetId}`); activeConnection.send('你好!我已成功连接你'); }); // 监听收到的消息 activeConnection.on('data', (data) => { addMessageToLog(`对方: ${data}`); }); // 连接错误处理 activeConnection.on('error', (err) => { alert(`连接失败: ${err.message}`); activeConnection = null; }); // 连接断开处理 activeConnection.on('close', () => { addMessageToLog('连接已断开'); activeConnection = null; }); } // 被动接收连接 peer.on('connection', (conn) => { // 关闭已有连接 if (activeConnection) { activeConnection.close(); } activeConnection = conn; addMessageToLog(`收到来自 ${conn.peer} 的连接`); // 监听收到的消息 activeConnection.on('data', (data) => { addMessageToLog(`对方: ${data}`); }); // 连接断开处理 activeConnection.on('close', () => { addMessageToLog('连接已断开'); activeConnection = null; }); }); // 发送消息 function sendMessage() { if (!activeConnection || !activeConnection.open) { alert('未建立有效连接,请先连接对方'); return; } const message = document.getElementById('messageInput').value.trim(); if (!message) return; activeConnection.send(message); addMessageToLog(`我: ${message}`); document.getElementById('messageInput').value = ''; } // 断开连接 function disconnectPeer() { if (activeConnection && activeConnection.open) { activeConnection.close(); } else { alert('当前无有效连接'); } } // 辅助函数:添加消息到日志 function addMessageToLog(text) { const logDiv = document.getElementById('messageLog'); const messageElement = document.createElement('div'); messageElement.textContent = text; logDiv.appendChild(messageElement); logDiv.scrollTop = logDiv.scrollHeight; }
核心修正说明
- 统一连接实例管理:用
activeConnection统一管理连接实例,无论主动发起还是被动接收连接,都将实例赋值给该变量,确保所有操作能正确调用。 - 完善状态与错误处理:新增
error、close事件监听,连接失败或断开时给出明确提示并重置状态。 - 优化消息展示:用消息日志区域替代alert,更直观地展示聊天记录。
- 增加输入校验:连接前检查Peer ID是否为空,发送消息前检查内容是否为空,避免无效操作。
- 处理重复连接:发起新连接前自动关闭已有连接,避免多连接冲突。
内容的提问来源于stack exchange,提问作者Abednego Nasila
相关产品推荐
相关产品推荐

