node 项目配置 https 和 wss

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

  • 安装

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 端口试下效果~
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值