Websocket 服务器打印对象对象而不是字符串

Websocket server prints object Object instead of a string

我正在使用 node.js 创建一个网站并使用 websocket。 客户端将图像作为字符串发送到服务器,服务器打印对象对象而不是字符串。问题出在哪里?

app.js

#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({ 
    httpServer: server });

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

var connections = {};
var connectionIDCounter = 0;

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    var connection = request.accept(null, request.origin);

    // Store a reference to the connection using an incrementing ID
    connection.id = connectionIDCounter ++;
    connections[connection.id] = connection;

    // Now you can access the connection with connections[id] and find out
    // the id for a connection with connection.id

    console.log((new Date()) + ' Connection ID ' + connection.id + ' accepted.');
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected. ' +
                    "Connection ID: " + connection.id);

        // Make sure to remove closed connections from the global pool
        delete connections[connection.id];
    });

    connection.on('message', function(message) {
        console.log((new Date()) + "Message received: " + message);//this prints object Object
        //sendToConnectionId(1, message);
    });
});



// Send a message to a connection by its connectionID
function sendToConnectionId(connectionID, data) {
    var connection = connections[connectionID];
    if (connection && connection.connected) {
        connection.send(data);
    }
}

这是 javascript 客户端

window.addEventListener("load", function() {

var ws;

var video = document.getElementById("videoElement");

var canvas = document.getElementById("canvas");

var playButton = document.getElementById("playButton");
var closeButton = document.getElementById("closeButton");

//log function
var log = function(msg){
    document.getElementById("log").innerHTML = msg;
}

navigator.getUserMedia = navigator.getUserMedia 
                        || navigator.webkitGetUserMedia 
                        || navigator.mozGetUserMedia 
                        || navigator.msGetUserMedia 
                        || navigator.oGetUserMedia;

if (navigator.getUserMedia) {       
    navigator.getUserMedia({video: true}, handleVideo, videoError);
}


function handleVideo(stream) {
    video.src = window.URL.createObjectURL(stream);
    video.play();
}

function videoError(e) {
    // do something
}

function disableButtons(disPlay, disClose){
    playButton.disabled = disPlay;
    closeButton.disabled = disClose;
}

//websocket connection
if('WebSocket' in window){
    connect("ws://127.0.0.1:8080");
}else{
    log("WebSocket not supported");
}
function connect(host){
    ws = new WebSocket(host);
    ws.onopen = function(){
        log("Connected to the server " + host);
    }
    ws.onclose = function(){
        log("Socket closed");
    }
    ws.onerror = function(evt){
        log('<span style="color: red;">ERROR:</span> ' + evt.data); 
    }
}
playButton.addEventListener("click", function() {
    disableButtons(true, false);
    video.play();
    setInterval(function() {
        canvas.getContext('2d').drawImage(video, 0, 0, 720, 480);
        var data = canvas.toDataURL('image/png').toString();
        ws.send(JSON.stringify(data.substr(0,50000)));

        //for test
        log(data.substr(0,50000));//this prints a string

    }, 100);

});

closeButton.addEventListener("click", function() {
    disableButtons(false, true);
    video.pause();
}, false);

}, false);

这与Websocket无关。这是因为使用 "string" + variableName 语法会导致变量被字符串化,而对象的默认字符串值为 [object Object]。要获取对象的实际内容,请更改

console.log((new Date()) + "Message received: " + message);

console.log(new Date(), "Message received:", message);

未测试,但我认为在 JSON 中你必须发送键值对,所以在客户端 js:

ws.send(JSON.stringify({imgdata: data.substr(0,50000)}));

并在服务器端尝试通过以下方式获取它:

  connection.on('message', function(message) {
        console.log((new Date()) + "Message received: " + message.imgdata);
        //sendToConnectionId(1, message);
    });

If you look at the source of the Websocket library you are using, you can see the object that is sent to the callback

message 有两个属性,消息中的数据类型和实际数据。这表明您实际上想要 message.utf8Data 而不仅仅是 message