方法1:
javascript
onLoad() {
uni.connectSocket({
url: 'ws://127.0.0.1:8000/ws/stat/realTimeStat/',
success: (res) => {
console.log('connect success', res);
}
});
uni.onSocketOpen(function (res) {
console.log('WebSocket连接已打开!');
uni.sendSocketMessage({
data: JSON.stringify({'username': 'realTimeStat', 'msg': 'stat'}),
success: (res) => {
console.log('send success', res);
}
});
});
uni.onSocketMessage(function (res) {
console.log('收到服务器内容:' + res.data);
})
uni.onSocketError(function (res) {
console.log('WebSocket连接打开失败,请检查!');
});
uni.onSocketClose(function (res) {
console.log('WebSocket 已关闭!');
});
},
方法2
javascript
onLoad() {
const socketTask = uni.connectSocket({
url: 'ws://127.0.0.1:8000/ws/stat/realTimeStat/',
success: (res) => {
console.log('connect success', res);
}
});
socketTask.onOpen(function (res) {
console.log('WebSocket连接已打开!');
socketTask.send({
data: JSON.stringify({'username': 'realTimeStat', 'msg': 'stat'}),
success: (res) => {
console.log('send success', res);
}
});
});
socketTask.onMessage(function (res) {
console.log('收到服务器内容:' + res.data);
})
socketTask.onError(function (res) {
console.log('WebSocket连接打开失败,请检查!');
});
socketTask.onClose(function (res) {
console.log('WebSocket 已关闭!');
});
},