//signalr得连接地址并携带token
let url = "ws://xxx/xxxHub"+ '?access_token=xxxx';
//开始连接
uni.connectSocket({
url: url,
method: 'GET',
success: function() {}
});
//连接成功
uni.onSocketOpen(function(res) {
//告诉服务器使用 JSON 的形式进行消息的序列化
uni.sendSocketMessage({
data: `{"protocol":"json", "version":1}${String.fromCharCode(0x1e)}`
});
console.log('WebSocket连接已打开!');
});
//连接失败
uni.onSocketError(function(res) {
console.log(res,'WebSocket连接打开失败,请检查!');
});
//接收到服务端消息
uni.onSocketMessage(function(res) {
var msg = res.data.replace(String.fromCharCode(0x1e), ""); //替换消息结束符
console.log("msg", msg)
let msgData = JSON.parse(msg)
//接收指定消息(这里为服务端得ReceiveMessage得消息,msgData.type === 1 为固定值表示调用客户端的一个方法)
if (msgData.type === 1 && msgData.target == "ReceiveMessage") {
console.log('收到服务器内容:' + JSON.stringify(msgData.arguments[0]));
}
});
//断开时得方法
uni.onSocketClose(function(res) {
console.log('WebSocket 已关闭!');
});
//执行服务端得方法 (methodName:方法名称,args:方法参数的值例如["张三","李四","王五"],type: 1 为固定值)
uni.sendSocketMessage({
data: `${JSON.stringify({arguments: args,target: methodName,type: 1,})}${String.fromCharCode(0x1e)}`
});