获取类型错误,说我的websocket变量未定义

时间:2016-11-12 12:50:50

标签: javascript websocket typeerror

我在我的页面中播放视频,并且我试图捕获帧并通过websocket将它们发送到服务器。

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

但是我的postVideoToServer()函数中出现以下错误:

  

" TypeError:clientSocket未定义"的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 个答案:

答案 0 :(得分:2)

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

 onclick="startRecording(video, clientSocket)"

clientSocket将是未定义的(您没有给它任何值)并且您无法从内部功能中更改它。