简体   繁体   English

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

[英]Websocket server prints object Object instead of a string

I'm creating a website with node.js and using websocket. 我正在使用node.js创建一个网站并使用websocket。 The client send an image as string to the server and the server prints object Object instead of a string. 客户端将图像作为字符串发送到服务器,服务器将打印对象Object而不是字符串。 Where is the problem? 问题出在哪儿?

app.js 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 这是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);

This has nothing to do with Websocket. 这与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] . 这是因为使用"string" + variableName语法会导致变量被字符串化,并且对象的默认字符串值为[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);

Not tested but I think in JSON you have to send key+value pairs, so on client side js: 未经测试,但我认为在JSON中您必须发送键值对,因此在客户端js上:

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

and on server side try to get it by: 并在服务器端尝试通过以下方式获取它:

  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 如果查看正在使用的Websocket库的源代码,则可以看到发送到回调的对象

message there has two properties, the type of data in the message, and the actual data. message有两个属性,即消息中的数据类型和实际数据。 This indicates that you actually want message.utf8Data instead of just message 这表明您实际上需要的是message.utf8Data而不是仅message

JavaScript 类型错误,将 object 打印为 '#<object> ' 细绳<div id="text_translate"><p>可能是一个幼稚的问题 - 如果执行此代码段(我正在使用 Node.js v12.16.3运行,除了错误类型之外,Chrome 的结果相同): </p><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> const obj = {} Object.defineProperty(obj, 'a', { writable: false, value: 13 }) obj.a = 14</pre></div></div><p></p><p> 显然,它会抛出一个错误,但该错误的消息字符串具有 object 的奇怪表示:</p><blockquote><p> TypeError:无法分配给 object '#&lt;Object&gt;' 的只读属性“a”</p></blockquote><p> 问题是 - 为什么它被字符串化为#&lt;Object&gt; ?</p><p> 在 object 上定义toString方法将呈现它,就好像它是用Object.prototype.toString.call(obj)调用的: </p><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> const obj = { toString () { return 'stringified obj' } } Object.defineProperty(obj, 'a', { writable: false, value: 13 }) console.log(`${obj}`) obj.a = 14</pre></div></div><p></p><blockquote><p> TypeError:无法分配给 object '[object Object]' 的只读属性 'a'</p></blockquote><p> 虽然console.log输出正确。 如何使TypeError output 成为正确的字符串表示形式? 它在内部使用什么?</p></div></object> - JavaScript TypeError, prints object as '#<Object>' string

暂无
暂无

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

相关问题 Websocket 发送 blob object 而不是字符串 - Websocket sending blob object instead of string 在列表中打印大量 [object Object] 而不是值 - Prints a lot of [object Object] in list instead of values Websocket 在实时服务器上发送 Blob object 并在本地服务器上发送字符串 - Websocket sending blob object on live server and string on local server JavaScript 类型错误,将 object 打印为 '#<object> ' 细绳<div id="text_translate"><p>可能是一个幼稚的问题 - 如果执行此代码段(我正在使用 Node.js v12.16.3运行,除了错误类型之外,Chrome 的结果相同): </p><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> const obj = {} Object.defineProperty(obj, 'a', { writable: false, value: 13 }) obj.a = 14</pre></div></div><p></p><p> 显然,它会抛出一个错误,但该错误的消息字符串具有 object 的奇怪表示:</p><blockquote><p> TypeError:无法分配给 object '#&lt;Object&gt;' 的只读属性“a”</p></blockquote><p> 问题是 - 为什么它被字符串化为#&lt;Object&gt; ?</p><p> 在 object 上定义toString方法将呈现它,就好像它是用Object.prototype.toString.call(obj)调用的: </p><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> const obj = { toString () { return 'stringified obj' } } Object.defineProperty(obj, 'a', { writable: false, value: 13 }) console.log(`${obj}`) obj.a = 14</pre></div></div><p></p><blockquote><p> TypeError:无法分配给 object '[object Object]' 的只读属性 'a'</p></blockquote><p> 虽然console.log输出正确。 如何使TypeError output 成为正确的字符串表示形式? 它在内部使用什么?</p></div></object> - JavaScript TypeError, prints object as '#<Object>' string jquery打印[object XMLDocument]而不是文件内容 - jquery prints [object XMLDocument] instead of file content 返回错误对象而不是解析器服务器中的字符串 - return error object instead of string in parser server 服务器将JavaScript对象写为字符串而不是整数 - Server writing out javascript object as string instead of integer javascript警报打印对象对象 - javascript alert prints Object Object 返回[Object object]而不是Reactjs中的Dom字符串 - Returns [Object object] instead Dom string in Reactjs JavaScript输出[object,object]而不是字符串 - JavaScript outputting [object, object] instead of string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM