需求:使用nodejs-websocket 建立一對一的即時通信服務
環境:nodejs
設計思想:保存消息通道,通過消息通道返回消息.
首先,要知道websocket 是什麼?
WebSocket建立在TCP協議之上,並且與HTTP協議有着良好的兼容性,最大的特點就是服務器可以主動向客戶端推送消息,客戶端也可以主動向服務器發送消息。
其次,nodejs-websocket 又是什麼?
看這裏https://www.npmjs.com/package/nodejs-websocket
既然都看到這裏了,說明對基礎已經掌握,so對node項目初始化、安裝nodejs-websocket不再贅述。
const ws = require('nodejs-websocket')
const PORT = 8000
// 通道
let AllConn = [{ userId: 'test001' }]
// 消息記錄
let messageList = []
// 創建一個服務
var server = ws.createServer(function (conn) {
console.log('New connection')
console.log(AllConn.length)
// 客戶端有消息的時候的回到函數
conn.on('text', function (str) {
const msg = JSON.parse(str)
// 建立通道
if (msg.type === 'get-pass') {
// 判斷是否存在
let exist = AllConn.some(item => {
return item.userId === msg.userId // true or false
})
if (exist) {
// 存在替換key
AllConn.forEach((item) => {
if (item.userId === msg.userId) {
item.wskey = conn.key
}
})
} else {
AllConn.push({
'userId': msg.userId,
'wskey': conn.key
})
conn.sendText(JSON.stringify({ code: '1', msg: '通道創建成功' }))
}
}
// 通過接收消息人標識,查找通道
if (msg.type === 'get-enter') {
// 組織需要發送的信息包
let conversations = {
formId: msg.userId,
toId: msg.toId,
msgUserId: msg.msgUserId, // 消息id = userId
content: msg.content,
createTime: msg.createTime,
timeStr: getMyTime(msg.createTime),
read: false
}
// 接收到消息返回
conn.sendText(JSON.stringify(conversations))
AllConn.forEach(item => {
// 通道存在
if (item.userId === msg.toId) {
// 獲取通道key,發送數據包
broadcast(conversations, item.wskey)
}
})
}
})
conn.on('close', (code, res) => {
// 客戶端斷開連接
console.log(conn.key + '已經斷開')
AllConn.forEach((item, index, arr) => {
if (item.wskey === conn.key) {
// 刪除通道記錄
arr.splice(index, 1)
}
})
})
conn.on('error', function (err) {
console.log('錯誤:' + JSON.stringify(err))
})
}).listen(PORT)
/**
* @description:廣播功能
* @param {Object} str 消息包
* @param {Object} wskey 通道key
* @return:
*/
function broadcast (str, wskey) {
// 遍歷所有通道
server.connections.forEach(conn => {
const key = conn.key
// 查找指定通道
if (key === wskey) {
conn.sendText(JSON.stringify(str))
}
})
}
/**
* @description: 時間戳轉時間
* @param {type}
* @return:
*/
function getMyTime (timestamp) {
let date = new Date(timestamp)
let hours = date.getHours()
let minutes = date.getMinutes()
return `${hours >= 10 ? hours : '0' + hours}:${minutes >= 10 ? minutes : '0' + minutes}`
}
如哪位大佬發現不完美、有誤及更好的方法.批評指正.