javascriptwebsocketwebcam-capture

Websocket server prints object Object instead of a string


I'm creating a website with node.js and using websocket. The client send an image as string to the server and the server prints object Object instead of a string. Where is the problem?

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);
    }
}

and this is the javascript client

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);

Solution

  • This has nothing to do with Websocket. It's because using the "string" + variableName syntax causes the variable to be stringified, and the default string value of an object is [object Object]. To get the actual contents of the object, change

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

    to

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