简体   繁体   English

如何从onmessage msg获取Websocket主机?

[英]How do I get the Websocket host from the onmessage msg?

I have multiple websocket servers that are communicating with a single page, and I'm running a list of callbacks to handle onmessage events from the servers. 我有多个Websocket服务器正在与一个页面进行通信,并且正在运行一个回调列表来处理服务器中的onmessage事件。 In order to reuse some functions for debugging I want to know where the messages are coming from from the msg object. 为了重用某些功能进行调试,我想知道消息来自msg对象的位置。

... ...

socket1Callbacks = $.Callbacks();
socket2Callbacks = $.Callbacks();
socket1Callbacks.add(logIncoming);
socket2Callbacks.add(logIncoming);

... ...

socket1.onmessage = function (msg) {
   socket1Callbacks.fire(msg);
};
socket2.onmessage = function (msg) {
    socket2Callbacks.fire(msg);
};

... ...

function logIncoming(msg) {
    console.log('MSG FROM HOST:' + msg.????host????);
    console.log('Recieved: ' + msg.data);
}

Inside the incoming message callback: 在传入的消息回调中:

socket2.onmessage = function (msg) {
    console.log(this.url); // the connected host
};

If you want need it inside logIncoming function, simply wrap the incoming message with your own object, containing the host: 如果您需要在logIncoming函数中使用它,只需将传入消息与您自己的包含主机的对象一起包装即可:

socket2.onmessage = function (msg) {
    socket2Callback.fire({ host: this.url, data: msg });
};

And then 接着

function logIncoming(msg) {
    console.log('MSG FROM HOST:' + msg.host);
    console.log('Received: ' + msg.data);
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM