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