本文共 1455 字,大约阅读时间需要 4 分钟。
为了让socket.io同时支持http和https,你需要配置两个不同的服务器实例,并将socket.io绑定到这两个服务器上。以下是详细的实现步骤:
首先,确保你已经安装了必要的依赖项:
npm install socket.io
接下来,创建两个服务器实例:
const http = require('http');const https = require('https');const fs = require('fs');const path = require('path');// 读取HTTPS证书文件const httpsOptions = { key: fs.readFileSync(path.join(__dirname, 'pem/openssl/ssl.key')), cert: fs.readFileSync(path.join(__dirname, 'pem/openssl/ssl.crt'))};// 创建HTTP服务器const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('Hello HTTP'); res.end();});// 创建HTTPS服务器const httpsServer = https.createServer(httpsOptions, (req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('Hello HTTPS'); res.end();}); 然后,初始化socket.io实例,并将其绑定到两个服务器上:
const io = require('socket.io')();// 绑定到HTTP服务器io.attach(server, { server: server, // 可以添加更多socket.io选项 cors: { origin: '*', methods: ['GET', 'POST'] }});// 绑定到HTTPS服务器io.attach(httpsServer, { server: httpsServer, cors: { origin: '*', methods: ['GET', 'POST'] }}); 这样做的好处是:
如果你需要在两个服务器上共享某些socket.io逻辑,可以考虑使用socket.io的中间件功能,将逻辑提取出来。
在实际应用中,建议:
这样配置后,你的应用将能够同时支持HTTP和HTTPS协议,并且socket.io功能在两个协议下都正常工作。
转载地址:http://ivjfk.baihongyu.com/