繁体   English   中英

缺少“套接字”上的错误处理程序。 node.js / socket.io

[英]missing error handler on 'socket'. node.js / socket.io

当我尝试从客户端接收数据时出现此错误,这是每秒更新一次的视频的视频时间。 我认为该错误正在客户端接收部分上发生,但我不确定如何解决。

这是错误

这是我的服务器代码:

var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');

var server = http.createServer(function(request, response){
var path = url.parse(request.url).pathname;

switch(path){
    case '/':
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write('hello world');
        response.end();
        break;
    case '/index.html':
        fs.readFile(__dirname + path, function(error, data){
            if (error){
                response.writeHead(404);
                response.write("opps this doesn't exist - 404");
                response.end();
            }
            else{
                response.writeHead(200, {"Content-Type": "text/html"});
                response.write(data, "utf8");
                response.end();
            }
        });
        break;
        case '/main.js':
        fs.readFile(__dirname + path, function(error, data){
            if (error){
                response.writeHead(404);
                response.write("opps this doesn't exist - 404");
                response.end();
            }
            else{
                response.writeHead(200, {"Content-Type": "text/html"});
                response.write(data, "utf8");
                response.end();
            }
        });
        break;
        case '/remote-clock.js':
        fs.readFile(__dirname + path, function(error, data){
            if (error){
                response.writeHead(404);
                response.write("opps this doesn't exist - 404");
                response.end();
            }
            else{
                response.writeHead(200, {"Content-Type": "text/html"});
                response.write(data, "utf8");
                response.end();
            }
        });
        break;
    default:
        response.writeHead(404);
        response.write("opps this doesn't exist - 404");
        response.end();
        break;
}
});

server.listen(25565);

io.listen(server);


var listener = io.listen(server);

listener.sockets.on('connection', function(socket){
  //send data to client
  setInterval(function(){
    socket.emit('date', {'date': new Date()});
  }, 1000);

  //recieve client data
  socket.on('client_data', function(data){
    process.stdout.write(data.letter);
 });
});

该客户代码为:

<!DOCTYPE html>
 <html>
    <head>


             <script src="/socket.io/socket.io.js"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE-edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, maximum-scale=1, width=device-width"/>
    <style type="text/css">
        body {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;

            padding: 0px;
            margin: 5%;
            width: 90%;
        }

        video {
            width: 100%;
        }

        #volume {
            width: 70%;
        }
    </style>
</head>
<body>
    <video id="video" autoplay>
        <source src="http://googledrive.com/host/0B-5FC9-wtiZzbTJFQnljdzNDdEE" type="video/mp4"/>
        <source src="http://googledrive.com/host/0B-5FC9-wtiZzbTJFQnljdzNDdEE" type="video/webm"/>
    </video>
    <div>
        <label>Volume: </label><input type="range" min="0" max="1" step="0.0001" value="1" id="volume"/>
        <button id="mute">Unmute</button>
        <button id="play">Play</button>

    </div>
    <div>Server Time: <span id="clock"></span></div>
    <div>Video Time: <span id="video-time"></span></div>
    <article>
        <h1>Synchronized Video Player</h1>
        <p><a href="" target="_blank">Open this page</a> in another browser window, even on another device, and the videos should be synchronized.</p>

    </article>


      <script>
      var video = document.getElementById('video');
  var socket = io.connect();
  socket.on('date', function(data){
    $('#date').text(data.date);
  });


   </script>
   <div id="date"></div>
  <textarea id="text"></textarea>


        <script src="http://cdn.jsdelivr.net/sockjs/0.3.4/sockjs.min.js">     </script>

        <script src="remote-clock.js"></script>
         <script src="main.js"></script>
    </body>
 </html>

我的main.js代码是:

(function (window) {
var CLOCK_PORT = 5001,
    EPSILON = -1 / 15,
    DURATION = 149.619,

    maxOffset = 1 / 30,
    video = document.getElementById('video'),
    clock = document.getElementById('clock'),
    videoTime = document.getElementById('video-time'),
    volume = document.getElementById('volume'),
    muted = document.getElementById('muted'),

    targetTime = 0,
    serverUrl,
    remoteClock,
    durationInMilliseconds,
    timeout,
    retries = 0,

    isBuffered;

function updateClockDisplay() {

    clock.textContent = (new Date(remoteClock.time())).toTimeString();
    videoTime.textContent = (video.currentTime).toFixed(2);
    requestAnimationFrame(updateClockDisplay);

  socket.emit('client_data', {'letter': videoTime});
  console.log(video.currentTime);


}

function checkAgain(delay) {
    clearTimeout(timeout);
    timeout = setTimeout(checkSync, delay);
}

function checkSync(evt) {
    var currentTime,
        current,
        currentBuffered,
        targetBuffered,
        targetDiff,
        currentDiff,
        skip;

    //currentTime is the time we should be at NOW
    currentTime = (remoteClock.time() % durationInMilliseconds) / 1000;

    //targetTime is the time we're seeking to and want to catch up to later
    //it's a little bit ahead of where we are so we can take time to buffer
    targetTime = Math.max(targetTime, currentTime);

    currentDiff = currentTime - video.currentTime;

    current = currentDiff > EPSILON && currentDiff < maxOffset;
    targetBuffered = isBuffered(targetTime);
    currentBuffered = isBuffered(currentTime) && isBuffered(currentTime + 2);

    if (currentBuffered && current) {
        video.play();
        retries = Math.min(2, retries);
        checkAgain(2000);
        return;
    }

    //we missed our window, so seek ahead and try again
    if (currentDiff >= EPSILON && video.readyState < 2 || currentDiff > 1) {
        skip = Math.pow(2, Math.min(4, Math.max(retries, 1)));
        targetTime = (currentTime + skip) % DURATION;
        video.pause();
        video.currentTime = targetTime;
        retries++;
        maxOffset = Math.max(maxOffset, retries * 0.1);
        checkAgain(1000);
        return;
    }

    //we haven't caught up yet, so give it a little more time to buffer and check in again
    targetDiff = targetTime - currentTime;
    checkAgain(targetDiff * 500);
}

function stateUpdate(evt) {
    if (!video.duration) {
        console.log('No video duration yet');
        video.pause();
        return;
    }

    console.log('video metadata', video.duration, video.videoWidth, video.videoHeight);
    durationInMilliseconds = Math.round(DURATION * 1000);
    if (remoteClock.accuracy() > 100) {
        return;
    }

    checkSync(evt || 'clock update');
}

function timeBuffered(time) {
    var i;
    if (!video.buffered) {
        return true;
    }

    for (i = 0; i < video.buffered.length; i++) {
        if (video.buffered.start(i) > time) {
            return false;
        }
        if (video.buffered.end(i) >= time) {
            return true;
        }
    }
    return false;
}



serverUrl = location.protocol + '//' + location.hostname + ':' + CLOCK_PORT + '/time-server';
remoteClock = new RemoteClock(serverUrl, stateUpdate);



video.muted = true;
video.addEventListener('durationchange', stateUpdate, false);
//video.addEventListener('waiting', stateUpdate, false);
//video.addEventListener('seeked', stateUpdate, false);
video.addEventListener('volumechange', function () {
    volume.value = video.volume;
    if (video.muted) {
        mute.textContent = 'Unmute';
    } else {
        mute.textContent = 'Mute';
    }
});
mute.addEventListener('click', function () {
    video.muted = !video.muted;
});
volume.addEventListener('input', function () {
    video.volume = volume.value;
});



play.addEventListener('click', function () {


    if (video.paused) {
        play.textContent = 'Play';
        video.play(); 
    } else {
        play.textContent = 'Pause';
        video.pause();
    }
});









window.addEventListener('touchstart', function touchstart(evt) {
    video.load();
    evt.preventDefault();
    window.removeEventListener('touchstart', touchstart, true);
}, true);
updateClockDisplay();
}(this));

错误出现在第80行,此行:

process.stdout.write(data.letter);

如果打开交互式节点会话并输入

process.stdout.write({a: "b"});

它给出了有关无效数据的错误,指出您不能将对象传递给process.stdout.write ,而只能传递字符串或缓冲区。 您正在向服务器发送{'letter': videoTime} ,并且videoTime引用HTML元素,它是一个对象。 您正在键入将HTML元素写入控制台。 如果要传递给服务器的是视频时间而不是保存视频时间的HTML元素,则可以将客户端代码更改为

{'letter': videoTime.textContent}

暂无
暂无

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

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