记录一下最近的工作成果: WebSocket没有想象中复杂,在前端就是几行代码的事,web端、原生小程序、uniapp都实践并且上线使用了。
- F12-网络展示效果,消息前面是用户id,判断对话框内容
- pc端部分代码
const ws = new WebSocket(`${api.URL.replace('http', 'ws')}/api/socket/qpb_connect?userid=${userStore.id}&identity=0`)
ws.onopen = function (evt) {
console.log('Connection open ...', evt)
ws.send('Hello WebSockets!')
}
ws.onmessage = async function (evt) {
console.log(`Received Message: ${evt.data}`)
const id = evt.data.slice(0, evt.data.indexOf('|'))
const cons = evt.data.slice(evt.data.indexOf('|') + 1)
await get_chat_list(columnNum.value)
await chatStore.getHomeCount()
if (Number.parseInt(id) === chatStore.chatObj.agency_user_id) {
chatRecord.value.push({
type: 1,
cons: cons.includes(api.URL) ? null : cons,
img_url: cons.includes(api.URL) ? cons : null,
})
addressBook.value[0].num_read_user = 0
api.get_chat_info({
// id: chatStore.chatObj.id,
user_id: chatStore.chatObj.user_id,
agency_id: chatStore.chatObj.agency_id,
is_agency: 0,
})
}
await nextTick(() => {
scrollRef.value.scrollBy(0, 1000000000)
})
}
ws.onclose = function (evt) {
console.log('Connection closed.', evt)
isCloseText.value = '网络已断开,请刷新!'
$message.error('网络已断开,请刷新!')
}
if (ws.readyState !== ws.OPEN) {
$message.error('网络已断开,请刷新后重新发送消息!')
return false
}
ws.send(`${chatStore.chatObj.agency_user_id}|${messageValue.value}`)
// 学微信的时间处理函数(今天内显示时分,昨天显示昨天,其余显示年月日)
const timeFun = (T) => {
const t = formatDateTime(T)
const today = formatDate(new Date())
const yes = formatDate(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), -1))
const long = `${t.slice(2, 4)}/${t.slice(5, 7)}/${t.slice(8, 10)}`
// console.log('时间', t, today, yes, long)
if (today === formatDate(t)) {
return t.slice(11, 16)
} else if (yes === formatDate(t)) {
return '昨天'
} else {
return long
}
}
3. 移动端部分业务代码,有些许bug,wx.onSocketOpen使用不正常
connectSocket() {
var that = this
// console.log('重新连接', baseUrl)
uni.connectSocket({
url: `${baseUrl.replace('http', 'ws')}/api/socket/xlc_connect?userid=${that.userInfo.id}&identity=0`,
header: {
'content-type': 'application/json'
},
success(res) {
console.log('WebSocket连接创建成功', res);
},
fail(res) {
console.log('WebSocket连接创建失败,请检查!', res);
}
})
uni.onSocketMessage(function(res) {
console.log('接收', res.data)
const id = res.data.slice(0, res.data.indexOf('|'))
const cons = res.data.slice(res.data.indexOf('|') + 1)
if (id != that.agency_id) return
that.arrty.push({
type: 1,
time_add: null,
cons: cons.includes('http') ? null : cons,
img_url: cons.includes('http') ? cons : null,
is_mp3: false
})
that.get_user_chat_msg()
// that.pageScrollToBottom();
})
uni.onSocketClose(function(res) {
console.log('关闭了了了了', res)
let pages = getCurrentPages()
if(pages.length > 0) {
let prevPage = pages[pages.length - 1]
// console.log('页面', prevPage.route )
if (prevPage.route == 'pages/message/messageInfo') {
uni.showModal({
title: '提醒',
content: '网络已断开,请刷新后重新发送消息!',
showCancel: false,
confirmText: '刷新',
complete: (res) => {
if (res.confirm) {
that.get_user_chat_msg()
that.connectSocket()
}
}
})
}
}
})
},
4. 附上几张截图