环境
- node.js (express)
- socket.io
基于express服务端框架,在本地搭建websocket服务
不适用于生产环境,请购买正规CA机构颁发的证书
生成证书
openssl genrsa -des3 -out server.pass.key 2048
openssl rsa -in server.pass.key -out server.key #生成私钥
openssl req -new -key server.key -out server.csr -subj "/C=CN/ST=Guangdong/L=ShenZhen/O=localhost/OU=localhost/CN=localshot" #生成证书签名请求
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt #生成证书
最后双击证书文件(server.crt),添加到信任列表
配置
- 创建index.js文件,指定证书和密钥的路径
//index.js
var express = require('express');
var app = express();
var path = require('path');
var fs = require('fs');
var https = require('https');
var options = {
key: fs.readFileSync('path/to/server.key'), //修改路径
cert: fs.readFileSync('path/to/server.crt'), //修改路径
};
var httpsServer = https.createServer(options, app);
var io = require('socket.io')(httpsServer);
httpsServer.listen(443, () => {
console.log('Https Server listening at port %d', 443);
});
app.get('/', function(req,res) {
res.send('hello world');
});
- 运行
node index.js
- 浏览器访问
https://localhost
网友评论