Nodejs搭建websocket(wss)+ MongoDB連接

const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const MongoClient = require('mongodb').MongoClient;
const DB_CONN_STR = 'mongodb://localhost:27017/microcosm'
// const qs = require('querystring');
 var userMap = new Map();
const server = https.createServer({
  cert: fs.readFileSync('D:/phpStudy/Apache/conf/ssl/dzchuanqi.crt'),
  key: fs.readFileSync('D:/phpStudy/Apache/conf/ssl/dzchuanqi.key'),
  passphrase:'123456'
});
const wss = new WebSocket.Server({ server });

MongoClient.connect(DB_CONN_STR,  {useNewUrlParser:true,useUnifiedTopology: true},function(err,db)
{
    if(err)
    {
        console.log("連接Mongodb錯誤:" + err);
    }
    else
    {
        console.log("連接mongdb成功!");
    }
});
 
wss.on('connection', function connection(ws) 
{
    console.log('client connected');
    ws.on('message', function incoming(message) 
    {
        console.log(message);
    });
 
    var sendMsg = new Buffer.from([2,0,1,9,0,9,0,1]);
    ws.send(sendMsg);
});
 
server.listen(5001);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章