Node.js HTTP服务器无法响应websocket

时间:2019-03-08 18:41:51

标签: node.js http websocket

http服务器未响应websocket

我无法让我的http服务器响应websocket请求。如何正确收听这些事件?我的服务器正在运行SPA,我想尝试并使用websocket不断地将更新的信息从文件发送到客户端。我已经通过SSE成功完成了此操作,但对websockets感到好奇。

我的server.js具有以下内容

const http = require('http');
const WebSocket = require('ws');

var server = http.createServer(function(request, response) {
   request.on('error', (err) => {
      console.error(err.stack);
   });
});

server.listen(8001);

const wss = new WebSocket.Server({ server });

wss.on('connection', function connection(ws) {
    ws.on('message', function message(msg) {
        console.log(msg);
      });
    });
});

我的client.js

var wsClient = ()=>{
    const ws = new WebSocket('ws:'+serverip+'/WSindexJSON'); // this server is set through XHR request

    ws.onopen = function(e) {
       console.log("Connection established");
    };

    ws.addEventListener('open', () => {
      // Send a message to the WebSocket server
      ws.send('Hello!');
    });
    console.log("ws open",ws)

    ws.addEventListener('message', event => {
      // The `event` object is a typical DOM event object, and the message data sent
      // by the server is stored in the `data` property
      console.log('Received:', event.data);
    });
}

我能够看到在chrome开发人员网络工具中创建的客户端网络套接字,但是服务器上没有任何内容。 我需要在服务器端创建websocket吗?

我看过另一个示例,服务器在监听升级事件。我尝试过但没有成功。

server.on('upgrade', function upgrade(request, socket, head) {
      const pathname = url.parse(request.url).pathname;
      console.log('server upgrade event websocket', pathname)
      if (pathname === '/WSindexJSON') {
        wss.handleUpgrade(request, socket, head, function done(ws) {
          wss.emit('connection', ws, request);
        });
      } else {
        socket.destroy();
      }
    });

我还尝试了另一个websocket模块const WebSocketServer = require('websocket').server;并遇到相同的问题。

1 个答案:

答案 0 :(得分:1)

您需要指定客户端尝试连接的端口(在您的情况下为8001):

var wsClient = ()=>{
    const ws = new WebSocket('ws:'+serverip+':8001/WSindexJSON');