socket.xu
封装一个socket插件玩
服务端
const ws = new WebSocketServer({port: 8888});
ws.defineUtil((connCaches) => {
return {
getAllUser() {
return Object.values(connCaches).map(connObj => connObj.user);
}
}
})
ws.onconnection((socket, utils) => {
// 登录事件
socket.$on('login', (data) => {
if (utils.checkLogin(data.user)) {
socket.$emit('login result', {
success: false,
message: '用户名已存在,请更换'
});
} else {
utils.login(socket, data.user, () => {
socket.$emit('login result', {
success: true,
message: '登陆成功',
historyMessage: utils.getHistoryMessage(),
});
ws.$broadcast('online update', {
onlineUsers: utils.getAllUser()
})
})
}
});
// 聊天事件
socket.$on('message', (data) => {
ws.$broadcast('new message', data);
});
// 注销事件
ws.ondisconection((data) => {
ws.$broadcast('user leave', {
user: data.user
});
ws.$broadcast('online update', {
onlineUsers: utils.getAllUser()
});
});
});
前端
var ws = new MyWebsocket(`ws://${location.hostname}:8888`);
ws.on('login result', (data) => {
if (data.success) {
this.currentUser = this.user;
this.messageArr = data.historyMessage;
this.$nextTick(()=> {
this.setChatArea();
});
} else {
this.user = '';
alert(data.message);
}
});
ws.on('new message', (data) => {
this.messageArr.push({
user: data.user,
message: data.message
});
this.$nextTick(()=> {
this.setChatArea();
});
});
ws.on('online update', (data) => {
this.onlineUsers = data.onlineUsers;
})
ws.$emit('message', {
user: this.currentUser,
message: chatMessage
});
示例代码如上