node 项目配置 https 和 wss

Nginx 配置 SSL 证书

node 配置

  • 将下载好的证书 (nginx 目录里的 .crt 和 .key 文件) 复制到 node 项目的 https 文件夹 (没有就新建个)


    node 项目配置 https 和 wss_第1张图片
  • 安装

npm i fs http https
  • app.js
const https = require('https');
const http = require('http');
const fs = require('fs');
const WebSocket = require('ws');

// 根据项目的路径导入生成的证书文件
const privateKey = fs.readFileSync('./https/certificate.key');
const certificate = fs.readFileSync('./https/certificate.crt');
const credentials = {
  key: privateKey,
  cert: certificate
};

// 创建 HTTP 与 HTTPS 服务器
const httpServer = http.createServer(app.callback());
const httpsServer = https.createServer(credentials, app.callback());

// 分别设置 HTTP HTTPS 的访问端口号
const PORT = 3030;
const SSLPORT = 3031;

// 创建 HTTP 服务器
httpServer.listen(PORT, function () {
  console.log('HTTP Server is running on: http://localhost:%s', PORT);
});

// 创建 HTTPS 服务器
httpsServer.listen(SSLPORT, function () {
  console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
});

const wss = new WebSocket.Server(
  {
    server: httpsServer
  },
  () => {
    console.log('socket start');
  }
);

// 建立连接
wss.on('connection', ws => {
  // 接收数据
  ws.on('message', msg => {
    // 广播
    wss.clients.forEach(function each(client) {
      if (client.readyState === WebSocket.OPEN) {
        client.send(msg);
      }
    });
  });
});

  • 用 https 和 wss 请求 3031 端口试下效果~

你可能感兴趣的:(node 项目配置 https 和 wss)