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

时间:2017-05-01 21:32:53

标签: javascript websocket webcam-capture

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

app.js

public static void Test()
{
    throw new Exception("Synchronous");
}

public static async void TestAsync()
{
    await Task.Yield();

    throw new Exception("Asynchronous");
}

public class EventSynchronizationContext : SynchronizationContext
{
    public override void Post(SendOrPostCallback d, object state)
    {
        if (state is ExceptionDispatchInfo
            && d.Target.GetType().ReflectedType.FullName == "System.Runtime.CompilerServices.AsyncMethodBuilderCore")
        {
            // Caught an exception
            var exceptionInfo = (ExceptionDispatchInfo)state;
            Console.WriteLine("Caught asynchronous exception: " + exceptionInfo.SourceException);

            return;
        }

        base.Post(d, state);
    }
}

static void Main(string[] args)
{
    SomeEvent += TestAsync;
    SomeEvent += Test;

    var previousSynchronizationContext = SynchronizationContext.Current;

    try
    {
        SynchronizationContext.SetSynchronizationContext(new EventSynchronizationContext());

        SomeEvent();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Caught synchronous exception: " + ex);
    }
    finally
    {
        SynchronizationContext.SetSynchronizationContext(previousSynchronizationContext);
    }

    Console.ReadLine();
}

这是javascript客户端

#!/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);
    }
}

3 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

未经测试但我认为在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);
    });

答案 2 :(得分:0)

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