【发布时间】:2017-05-24 19:30:07
【问题描述】:
我正在尝试学习 webrtc 及其第一次尝试,我正在尝试使用 webRTC 创建基于文本的聊天,在经历了很多教程/提示后,我尝试了下面的代码,现在唯一的问题是我可以发送/使用控制台(代码中的window.say)在对等点之间接收文本消息,但是当我尝试使其在HTML表单中工作时,它仅适用于第一个对等点发送消息
这是我的代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Live Chat</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
</head>
<body>
<button id="start_chat" name="start_chat">Start Chat</button>
<textarea rows="20" cols="30" id="chatBox"></textarea>
<br>
<input type="text" name="send_text" id="send_text">
<button id="send_btn" name="send_btn">Send</button>
<script>
var dataChannel;
$(function(){
var peerConn = new RTCPeerConnection({'iceServers': [{'urls': ['stun:stun.l.google.com:19302']}]});
function create(which_channel)
{
console.log("Creating ...");
dataChannel = peerConn.createDataChannel(which_channel);
dataChannel.onopen = (e) => {
window.say = (msg) => { dataChannel.send(msg); };
console.log('Say things with say("hi")');
};
dataChannel.onmessage = (e) => {
$("#chatBox").append(e.data);
console.log('Got message:', e.data);
};
peerConn.createOffer({})
.then((desc) => peerConn.setLocalDescription(desc))
.then(() => {})
.catch((err) => console.error(err));
peerConn.onicecandidate = (e) => {
if (e.candidate == null) {
console.log("Get joiners to call: ", "join(", JSON.stringify(peerConn.localDescription), ")");
}
};
}
function gotAnswer(answer) {
console.log("gotAnswer Initializing ...");
peerConn.setRemoteDescription(new RTCSessionDescription(JSON.parse(answer)));
};
function join(offer) {
console.log("Joining ...");
peerConn.ondatachannel = (e) => {
console.log("Joining2 ...");
var dataChannel = e.channel;
dataChannel.onopen = (e) => {
window.say = (msg) => { dataChannel.send(msg); };
console.log('Say things with say("hi")');
};
dataChannel.onmessage = (e) => {
$("#chatBox").append(e.data);
console.log('Got message:', e.data);
}
};
peerConn.onicecandidate = (e) => {
console.log("Joining3 ...");
if (e.candidate == null) {
console.log("Get the creator to call: gotAnswer(", JSON.stringify(peerConn.localDescription), ")");
}
};
var offerDesc = new RTCSessionDescription(JSON.parse(offer));
peerConn.setRemoteDescription(offerDesc);
peerConn.createAnswer({})
.then((answerDesc) => peerConn.setLocalDescription(answerDesc))
.catch((err) => console.warn("Couldn't create answer"));
}
$("#start_chat").click(function(){
create("something");
});
$("#send_btn").click(function(){
msg = $("#send_text").val();
$("#chatBox").append(msg);
dataChannel.send(msg);
});
});
</script>
</body>
</html>
上面的例子是通过控制台命令工作的,现在当我尝试使用 $("#send_btn").click() 函数发送消息时,第一个对等点(启动会话)可以发送消息。
第二个对等点在单击“#send_btn”时收到此错误。
dataChannel is undefined
但是第二个对等点可以使用控制台向第一个对等点发送消息。
P.S 您知道如何在此实现音频通话吗?我想要一个按钮来进行音频通话,它不应该影响我的聊天频道,我应该打开一个新的对等连接吗?
【问题讨论】:
标签: javascript webrtc