我的页面正在播放视频,我正在尝试捕获帧并通过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.");
};
}
当我点击
下面的按钮时,开始录制功能被触发<button onclick="startRecording(video)" class="recordbutton">Turn camera on</button>
您需要从所有函数中删除clientSocket参数,只使用全局变量。因为即使你调用:
onclick="startRecording(video, clientSocket)"
clientSocket将是未定义的(你没有传递任何值),你不能从函数内部改变它。