我的页面上正在播放视频,并且试图捕获帧并将其通过Websocket发送到服务器。

我已经成功完成了与Websocket握手的连接,并与服务器建立了连接。

但是我在postVideoToServer()函数中收到以下错误:


  “ TypeError:clientSocket未定义” index.html:60:5


客户端套接字实际上是客户端用来与服务器通信的套接字。我已经在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>

最佳答案

您需要从所有函数中删除clientSocket参数,而仅使用全局变量。因为即使您打电话:

 onclick="startRecording(video, clientSocket)"


clientSocket将是未定义的(您未赋予任何值),并且无法从内部函数中对其进行更改。

09-19 07:46