【问题标题】:why websocket connection creation does not pass through http?为什么websocket连接创建不通过http?
【发布时间】:2016-10-13 10:12:58
【问题描述】:

我偶然发现了 websocket 和 http。

我写了下面的例子:

var fs   = require('fs');

var server = http.createServer(function(request, response) {
  console.log ("HTTP Request created...");
  // I am responding something here..
});

server.listen(1234, function() {
   console.log((new Date()) + ' Server is listening on port 1234');
});


var WebSocketServer = require('websocket').server;
wsServer = new WebSocketServer({
            httpServer: server
});

wsServer.on('request', function(re){
        var conn = re.accept(null, re.origin);
            console.log ("Accepted New Connection..");
            conn.on('message', function(message) {
                console.log ('message received' + message.utf8Data);
            });
           });

我尝试了两种方式连接到这个服务器。

1) Through Browser.
2) through node.js application 

当我尝试通过浏览器访问此服务器时,例如:http:IP:1234, 我得到“HTTP Request received..”被打印出来,当我尝试使用时 在 Node.js 中的代码下方,我没有看到此消息被打印出来。

var WebSocket = require('ws')
  ws = new WebSocket('ws://IP:1234');

    ws.on('open', function() {
            console.log ("WebSocket opened..");
            ws.send('something');
    });
ws.on('message', function(message) {
        console.log('received: %s', message.data);
});

当我尝试通过
连接到网络服务器时 ws = new WebSocket('ws://IP:1234');

为什么它没有通过 HTTP?我的基本理解是 Websocket 只是 HTTP 之上的升级,在这种情况下,我会假设 WebSocket() 反过来通过 HTTP 连接到服务器对吗?还是我很困惑?

【问题讨论】:

    标签: javascript node.js html tcp websocket


    【解决方案1】:

    Websocket 请求不会在 HTTP 服务器实例上触发 request 事件(您传递给 createServer 的函数是一个侦听器)。

    如果你想在 HTTP 服务器上监听 websocket 请求,监听 upgrade 事件:

    server.on('upgrade', function (req, socket, head) { ... });
    

    我认为这是因为 http 将自己处理握手/升级,所以这是通过不同的事件完成的。

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 2021-12-15
      相关资源
      最近更新 更多