1. 前言 看WEBRTC教程时使用到WebSocket来传输信令,node端使用了ws库来实现,但在浏览器端http无法获取本地媒体,必须使用https,使用https后webSocket 不能使用ws协议了,必须使用wss协议。
2. 证书选择 网上看到的教程里使用的SSL证书都是适用于nginx下的两个证书,但我使用时总是碰到问题,webSocket连接时都发生段错误,所以我使用了不同的证书:适用于IIS的两个证书:youtdomain.pfx keystorePass.txt。
3. 实现代码
// 需安装ws模块 npm install ws let WebSocketServer = require('ws').Server; let https = require("https"); let fs = require("fs"); let pfxpath = __dirname + '/test.com.pfx'; // let passpath = __dirname + '/testkey.txt'; let options = { pfx: fs.readFileSync(pfxpath), passphrase: fs.readFileSync(passpath), }; let server = https.createServer(options, (req, res) => { res.writeHead(200); res.end("this is a websocket server \n"); }).listen(8888); let wss = new WebSocketServer({ server: server }); wss.on( "connection", connection => { console.log("has user to connected"); } );