websockets - 带节点的ws

时间:2015-04-15 09:49:06

标签: javascript node.js websocket

我正在尝试使用node.js应用程序中的ws模块将消息从服​​务器推送到客户端。

请在下面找到app.js中的代码。

var server = app.listen(port);
var WebSocketServer = require('ws').Server
var wss = new WebSocketServer({ server: server});
wss.on('connection', function (ws) {

    console.log('connected');
});

ws.on('message', function (data, flags) {

});

});

客户端js文件中的代码。

    window.WebSocket = window.WebSocket || window.MozWebSocket;
    var host = window.document.location.host.replace(/:.*/, '');
    var port = window.document.location.port;
    var socketConnection = new WebSocket('ws://'+ host+':'+ port);        
    socketConnection.onerror = function (error) {
        // TODO : report error here..
    };         
    socketConnection.onmessage = function (message) {
            var obj = JSON.parse(message.data)          

    };

问题是当我在local.i.e http://localhost:port运行节点应用程序时,当我尝试通过“ws:// localhost:port \”与ws连接握手时。握手发生,我能够发送和接收消息。

但是当我使用我的机器的ip访问相同的应用程序时,即http://10.xx.yy.zz:port。我能够打开应用程序并做一些事情,但与websockets的握手超时。当应用程序在另一台机器上运行并尝试从我的机​​器浏览器连接到它时也会发生同样的情况。握手不会发生并且超时。

我已经尝试过与ws模块开箱即用的演示相同的内容。同样的事情发生了我在创建websocket服务器时遗漏了什么?

0 个答案:

没有答案
相关问题