繁体   English   中英

收到类型错误,提示我的websocket变量未定义

[英]Getting a type error saying my websocket variable is undefined

我的页面上正在播放视频,并且试图捕获帧并将它们通过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将是未定义的(您没有给它赋任何值),并且不能从函数内部更改它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM