Uni-app插件下载链接(兼容小程序):
npm i @hyoga/uni-socket.io --save
PC版连接例子:
引入socketIo
<script src="socket.io.js"></script>
创建连接:
var socket = new io('http://服务器IP:端口号?token=TOKEN', {
transports: [ 'websocket']
});
监听事件:
监听连接成功事件
socket.on('connect', function() {
console.log("连接成功");
socket.emit('conn',{ uid: "会员ID" })
});
监听自己的注册状态,
注册成功后才可接收消息
socket.on('conn', function (data) {
if(data[0] == 'ok'){
console.log('注册成功' )
} else{
console.log('注册失败' )
}
});
监听断线重连
socket.on('reconnect', function() {
console.log("重连成功");
});
监听断线
socket.on('disconnect', function() {
console.log("已下线");
});
监听全部会员的上线广播
socket.on('login', function(data) {
console.log("会员上线",data.uid);
});
监听全部会员的下线广播
socket.on('loginout', function(data) {
console.log("会员下线",data.uid);
});
接收消息
socket.on('broadcastingListen', function (data) {
for(i=0;i<data.length;i++){
console.log(data[i])
}
});
接收警告消息
socket.on('notice', function (data) {
console.log(data)
});
发送消息:
单发
socket.emit("sendmsg",{
"to_id": "接收人会员ID",
"msg": "消息内容",
"msg_type": "1"
})
群发
socket.emit("sendall",{
"room":"room1",
"message":"Hello"
})
注销socket
socket.disconnect();
socket = null;