websockets,用来自服务器的消息更新div

时间:2012-08-12 02:06:06

标签: javascript html5 node.js websocket

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.');
    });
});

由于

1 个答案:

答案 0 :(得分:3)

每个标签/窗口打开自己的标识符websocket,您的服务器应该向当前用户打开的所有网页框发送消息。

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