收到类型错误,提示我的 websocket 变量未定义
2016-11-12
1111
我的页面上正在播放视频,我正在尝试捕获帧并通过 websocket 将它们发送到服务器。
我已经成功与服务器建立了连接,并且还完成了 websocket 握手。
但是我在
postVideoToServer()
函数中收到以下错误:
"TypeError: clientSocket is undefined" index.html:60:5
clientsocket 实际上是客户端用于与服务器通信的套接字。我已经在
clientSocket.onopen
中使用此变量成功将数据发送到服务器。
我做了一些研究,发现这意味着值不是预期的类型。这对我来说仍然没有意义。任何解释都将不胜感激。
这是我的 js 代码的一部分。如果需要更多信息,请告诉我。
var bStop = true;
var bOldBrowser = false;
var video;
var streamRecorder;
var webcamstream;
var clientSocket;
function postVideoToServer(clientSocket,frame)
{
clientSocket.send(frame);
}
function draw(v, cc, w, h, c, clientSocket)
{
cc.drawImage(v, 0, 0, w, h); //draw video frame on canvas
var frameData =c.toDataURL(); //turn canvas to raw png format
postVideoToServer(clientSocket,frameData);
if(!bStop)
setTimeout( function() { draw(v, cc, w, h, c, clientSocket) }, 40); //40 * 25 = 1000 ==> draw canvas every 40 ms to have 25FPS
}
function startRecording(video, clientSocket)
{
video = document.querySelector('video');
var canvas = document.getElementById('canvas');
var canvasContext = canvas.getContext('2d');
var width = video.videoWidth;
var height = video.videoHeight;
canvas.width = width;
canvas.height = height;
bStop = false;
//establish connection with server
establishSocketConnection(clientSocket,"ws://localhost:3000/web/project/Server.php");
draw(video, canvasContext, width, height, canvas, clientSocket)
}
function establishSocketConnection(clientSocket,URL)
{
clientSocket = new WebSocket(URL); //create socket to server
clientSocket.onopen = function (e)
{
console.log("socket open");
}
clientSocket.onclose = function (e)
{
console.log("Socket connection closed : "+e);
}
clientSocket.onerror = function(error)
{
alert("Failed to connect to server...Please try again later.");
};
}
当我点击下面的按钮时,会触发 startRecording 函数
<button onclick="startRecording(video)" class="recordbutton">Turn camera on</button>
1个回答
您需要从所有函数中删除 clientSocket 参数并仅使用全局变量。因为即使您调用:
onclick="startRecording(video, clientSocket)"
clientSocket 将未定义(您没有为其分配任何值)并且您无法从函数内部更改它。
jcubic
2016-11-12