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");
}
);
4. 相關問題
運行wss的服務器必須是SSL證書域名解析到的服務器。否則會出現錯誤,當本地測試時可以使用ws協議。