【问题标题】:Creating wss socket with ws npm library - error: socket hang up使用 ws npm 库创建 wss 套接字 - 错误:套接字挂起
【发布时间】:2020-01-11 04:12:17
【问题描述】:

有没有一种方法可以创建并连接到路径中接受wss 而不仅仅是ws 的websocket 服务器?

我目前正在使用ws npm 库来执行以下操作:

const wss = new WebSocket.Server({port: 8080});

wss.on('connection', () => {
    console.log('connected!');
});

然后在终端连接:

wscat -c ws://localhost:8080

我会成功连接并获得正确的日志消息。

但是我想要/需要连接到 wss websocket,但无法使其与 ws npm 库一起使用。

wscat -c wss://localhost:8080

这会返回错误:error: socket hang up

有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: javascript node.js typescript npm websocket


    【解决方案1】:

    您需要打开一个 HTTPS 服务器才能连接到它。 这在ws的文档中也有说明。

    const fs = require('fs');
    const https = require('https');
    const WebSocket = require('ws');
    
    const server = https.createServer({
      cert: fs.readFileSync('/path/to/cert.pem'),
      key: fs.readFileSync('/path/to/key.pem')
    });
    const wss = new WebSocket.Server({ server });
    
    wss.on('connection', function connection(ws) {
      ws.on('message', function incoming(message) {
        console.log('received: %s', message);
      });
    
      ws.send('something');
    });
    
    server.listen(8080);
    
    

    WS with HTTPS

    您可以使用Let's Encrypt 创建证书

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 2014-10-02
      • 2015-08-27
      • 1970-01-01
      • 2018-01-29
      • 2019-10-14
      • 1970-01-01
      相关资源
      最近更新 更多