Nodejs搭建wss服務器


首先使用OpenSSL創建自簽名證書:

#生成私鑰key文件
openssl genrsa 1024 > /path/to/private.pem
//
#通過私鑰文件生成CSR證書簽名
openssl req -new -key /path/to/private.pem -out csr.pem
//
#通過私鑰文件和CSR證書簽名生成證書文件
openssl x509 -req -days 365 -in csr.pem -signkey /path/to/private.pem -out /path/to/file.crt

使用ws模塊創建wss服務器:

var https=require('https');
var ws=require('ws');
var fs=require('fs');
var keypath=process.cwd()+'/server.key';//我把秘鑰文件放在運行命令的目錄下測試
var certpath=process.cwd()+'/server.crt';//console.log(keypath);
//console.log(certpath);
 
var options = {
  key: fs.readFileSync(keypath),
  cert: fs.readFileSync(certpath),
  passphrase:'1234'//如果秘鑰文件有密碼的話,用這個屬性設置密碼
};
 
var server=https.createServer(options, function (req, res) {//要是單純的https連接的話就會返回這個東西
    res.writeHead(403);//403即可
    res.end("This is a  WebSockets server!\n");
}).listen(15449);
 
 
var wss = new ws.Server( { server: server } );//把創建好的https服務器丟進websocket的創建函數里,ws會用這個服務器來創建wss服務
//同樣,如果丟進去的是個http服務的話那么創建出來的還是無加密的ws服務
wss.on( 'connection', function ( wsConnect ) {
    wsConnect.on( 'message', function ( message ) {
        console.log( message );
    });
});

客戶端鏈接:

var ws = new WebSocket('wss://localhost:15449/', {
  protocolVersion: 8,
  origin: 'https://localhost:15449',
  rejectUnauthorized: false //重要,自簽名證書只能這樣設了。CA頒發的受信任證書就不需要了
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM