服务端
~~~
// index.js
const io = require('socket.io')(8228)
io
.of('/chat')
.on('connection', socket => {
socket.on('getUser', data => {
socket.broadcast.emit('getMsg', {
msg: '欢迎' + data.userName + '加入群聊',
userName: '智能AI'
})
socket.emit('getMsg', {
msg: '你已加入群聊',
userName: '智能AI'
})
socket.on('sendMsg', (data) => {
console.log('data', data)
if (data.private) {
socket.emit('getPrivateMsg', data)
} else {
// 全部可见
chat.emit('getMsg', data)
}
})
socket.on('exit', (name) => {
const msg = name + '已经退出群聊'
socket.broadcast.emit('getMsg', {
msg,
userName: "智能AI"
})
})
socket.on('disconnect', function () {
// ...
})
})
~~~
客户端
~~~
// socket.js
const io = require('socket.io-client')
export const setConnect = () => {
const socket = io.connect('http://localhost:8228/chat')
window.socket = socket
}
~~~
~~~
// chat.js
import { setConnect } from '@/utils/socket.js'
export default class Chat {
constructor() {
this.chats = []
this.privateChats = []
this._init()
}
_init() {
const _this = this
window.socket.emit('getUser', {
userName: window.userName
})
window.socket.on('getMsg', (data) => {
_this.chats.push(data)
})
window.socket.on('getPrivateMsg', (data) => {
_this.privateChats.push(data)
})
}
exit(name) {
window.socket.emit('exit', name)
window.socket.close(name)
}
sendMsg(msg, isPub = true, to) {
window.socket.emit('sendMsg', {
userName: window.userName,
private: !isPub,
msg,
to
})
}
reConnect() {
setConnect()
this._init()
}
}
~~~