简单、粗暴、直接上步骤
(1) 后端提供的WebSocket地址是否能正常连接成功,在线测试网址。
(2) uni-app连接 websocket 官方文档。
(3) Websocket相关方法
① 连接
uni.connectSocket(OBJECT)
② 打开
uni.onSocketOpen(CALLBACK)
③ 发送
uni.sendSocketMessage(OBJECT)
④ 接收
uni.onSocketMessage(CALLBACK)
⑤ 关闭
uni.closeSocket(OBJECT)
(4) 代码示例
① 在store/module目录下创建全局 websocket.js
const websocket = {
state: {
websock: null,
hasConnected: false,
},
mutations: {
setConnection(state, websock) {
state.websock = websock
},
sethasConnected(state, hasConnected) {
state.hasConnected = hasConnected;
}
},
getters: {
STAFF_UPDATE(state) {
return state.websock
}
},
actions: {
STAFF_WEBSOCKET({
state,
commit
}) {
return new Promise(async (resolve, reject) => {
let socketTask = uni.connectSocket({
url: 'ws://serveraddress/ws',
header: {
'content-type': 'application/json'
},
success: function() {
console.log("连接成功");
}
})
commit('setConnection', socketTask);
commit('sethasConnected', true);
//连接
websocket.state.websock.onOpen((res) => {
console.log("连接正常" + res);
const userid = uni.getStorageSync('userid');
let actions = {
SenderID: userid,
ReceiverID: "",
Content: "",
MessageType: "",
TableRowGuid: "",
MessageType: ""
};
websocket.state.websock.send({
data: JSON.stringify(actions),
success: () => {
console.log("发送成功");
}
});
});
//接收消息
websocket.state.websock.onMessage(function(res) {
console.log("接收服务器消息:" + res.data)
})
//关闭
websocket.state.websock.onClose((res) => {
console.log("关闭");
})
//异常
websocket.state.websock.onError((res) => {
console.log("异常");
})
});
}
}
}
export default websocket
② 在store/index.js引用 websocket.js 并注入
③ App.vue文件中初始化连接方法
(5) 遇到的坑?
① 地址错误
服务器接口是ws://协议,小程序中必须是 wss:// 协议
② 由小程序项目转换的uni-app项目 , 连接失败
浏览器运行直接访问需访问https协议的,更改 Server 协议
若不更改Server协议,需连手机端直接调试,不得使用浏览器直接运行