【问题标题】:websockets, updating div with messages from serverwebsockets,使用来自服务器的消息更新 div
【发布时间】:2012-08-08 18:55:54
【问题描述】:
websocket.onmessage = function (evt) { 
    console.log('Retrieved data from server: ' + evt.data); 
    $('#someDiv').append(evt.data);
};

如果我在浏览器中打开 2 个选项卡,为什么此事件仅在我发送消息的活动选项卡中触发?由于数据是从服务器接收的,这不应该同时在两个选项卡中触发吗?

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,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

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('echo-protocol', request.origin);
    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

谢谢

【问题讨论】:

  • 您是否尝试在两个浏览器中打开它?浏览器通常会将 Web 套接字连接数限制到单个域,因此第二个选项卡可能无法连接。
  • @numbers1311407 是的,我已经试过了:/。我在服务器中的两个选项卡中都看到“已接受连接”。不过谢谢
  • 你的服务器端代码是什么样的?
  • @BrandonTilley 更新问题

标签: javascript html node.js websocket


【解决方案1】:

每个选项卡/窗口都使用自己的标识符打开自己的 websocket,您的服务器应该向当前用户打开的所有 websocket 发送消息。

在您仅将消息发送到第一个连接的 websocket 的情况下,您可以使用 window.localStorage 作为消息缓冲区在同一域上的选项卡/窗口之间共享数据。 store.js 可以帮助您将对象放入 localStorage 并检索它们,并确保跨浏览器兼容性)。然后为函数调用设置一个间隔,它会定期查找新消息。

【讨论】:

  • 感谢您的回答。如果我使用你的 localstorage 选项,我不妨完全跳过 websocket 部分,因为没有它它也能正常工作。在所有在线示例中,我可以通过多个选项卡与自己联系和聊天,我的代码有什么不同?
  • 你用这个库处理websocketsgithub.com/Worlize/WebSocket-Node吗?
  • 我认为我只使用 node.js atm。例如,我将如何安装 socket.io?
  • 然后查看socket.io/#how-to-use,即带有socket.on('设置昵称',...的示例您可以在连接后同样设置user_id并将所有用户的套接字保存在集合中,如{user1_id:user1_sockets , user2_id:user2_sockets/*, etc...*/},然后向所有用户的套接字广播/发送消息。
  • 昨晚在 SO 上还有一些其他问题表明 NPM 存储库正在抛出 404 问题;今天再试一次,看看你得到了什么。 :)
猜你喜欢
  • 2011-05-25
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 1970-01-01
  • 2013-05-31
  • 2020-12-15
  • 2012-02-16
  • 2021-07-06
相关资源
最近更新 更多