我正在尝试制作一个webrtc视频应用。 在客户端代码中,我有:
getUserMedia(constraints, handlemedia, errorhandle);
constraints = {video: true};
function handlemedia(stream){
//other stuff I do here
document.getElementById("connect").addEventListener("click", function(e){
var socket = io.connect();
}
var servers = {"iceServers": [{ "url": "stun:localhost:2013"}]};
pc = new RTCPeerConnection(servers);
pc.onicecandidate = function (evt, socket) {
console.log("THIS IS THE evt.candidate: ", evt.candidate);
somecandidate = evt.candidate;
socket.emit( "candidate", somecandidate );
};
pc.addStream(localStream);
function gotDescription(desc, socket) {
console.log("WE GOT THE DESC.");
pc.setLocalDescription(desc);
socket.emit( "sdp", desc);
}
document.getElementById("createoffer").addEventListener("click", function(e){
pc.createOffer(gotDescription);
});
}
然后在server.js(在node.js中)代码我有:
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket){
socket.on("candidate", function(somecandidate){
console.log("GOT CANDIDATE.");
});
socket.on("sdp", function(desc){
console.log("Got desc");
});
});
我意识到我现在只是使用按钮,但它现在只是为了让我可以简单地测试它。我只需要将整个webrtc事情搞定。
因此,如果我运行此代码,它会在浏览器控制台中显示“无法读取未定义的属性'emit'。很明显,它不喜欢socket.emit的东西。为什么不呢?它对socket有什么不同。发射?
答案 0 :(得分:0)
document.getElementById("connect").addEventListener("click", function(e){
var socket = io.connect();
}
var
将变量定义在函数中。此处的socket
仅在此函数中可见。
pc.onicecandidate = function (evt, socket) {
console.log("THIS IS THE evt.candidate: ", evt.candidate);
somecandidate = evt.candidate;
socket.emit( "candidate", somecandidate );
};
上述var socket
在此处不可见,因此socket
将为undefined
。
因此,在您的情况下,按钮实际上使其更难以使用。你根本不使用它们会更好:
getUserMedia(constraints, handlemedia, errorhandle);
constraints = {video: true};
function handlemedia(stream){
//other stuff I do here
var socket = io.connect();
// Start the RTCPeerConnection and candidate gathering
// after we've done io.connect()
var servers = {"iceServers": [{ "url": "stun:localhost:2013"}]};
pc = new RTCPeerConnection(servers);
pc.onicecandidate = function (evt, socket) {
console.log("THIS IS THE evt.candidate: ", evt.candidate);
somecandidate = evt.candidate;
socket.emit( "candidate", somecandidate );
};
pc.addStream(localStream);
function gotDescription(desc, socket) {
console.log("WE GOT THE DESC.");
pc.setLocalDescription(desc);
socket.emit( "sdp", desc);
}
pc.createOffer(gotDescription);
}
如果你真的想要按钮,那么将上面的全部内容包装到一个你将用作点击处理程序的函数中,而不是仅仅将var socket = io.connect()
放入处理程序中。