singelR连接实现通信聊天
singelR是什么?
SignalR是一个基于ASP.NET平台构建,利用JavaScript或者WebSockets,实现在客户端和服务端异步通信的框架(https://docs.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-3.0&tabs=visual-studio)
简单使用:
SignalR会使用Javascript的长轮询( long polling),实现客户端和服务端通信 前端通过(CarPositionChanged)像服务器发送一段数据,服务器接收后,再通过(RegisterClient)给前端推送相应的数据,整个过程中页面不会刷新
utils文件下的websocket.js文件
var senparcWebSocketConnection;
function buildConnectionAndStart(hubUrl, signalR, onStart, errorCallback,stickyCookie) {
senparcWebSocketConnection = new signalR.HubConnectionBuilder()
.withUrl(hubUrl)
.build(stickyCookie);
senparcWebSocketConnection.start(onStart()).then().catch(function (err) {
console.error(err.toString());
if (errorCallback) {
errorCallback();
}
});
return senparcWebSocketConnection;
}
function requestServer(methodName, submitData) {
senparcWebSocketConnection.invoke(methodName, submitData).catch(function (err) {
return console.error(err.toString());
});
}
function onReceiveMessage(methodName, receiveFunction) {
senparcWebSocketConnection.on(methodName, function (res) {
receiveFunction(res);
});
}
module.exports = {
buildConnectionAndStart: buildConnectionAndStart,
requestServer: requestServer,
onReceiveMessage: onReceiveMessage
}
utils文件下的onfire.js文件
!function (root, factory) {
if (typeof module === 'object' && module.exports)
module.exports = factory();
else
root.onfire = factory();
}(typeof window !== 'undefined' ? window : this, function () {
var __onfireEvents = {},
__cnt = 0,
string_str = 'string',
function_str = 'function',
hasOwnKey = Function.call.bind(Object.hasOwnProperty),
slice = Function.call.bind(Array.prototype.slice);
function _bind(eventName, callback, is_one, context) {
if (typeof eventName !== string_str || typeof callback !== function_str) {
throw new Error('args: '+string_str+', '+function_str+'');
}
if (! hasOwnKey(__onfireEvents, eventName)) {
__onfireEvents[eventName] = {};
}
__onfireEvents[eventName][++__cnt] = [callback, is_one, context];
return [eventName, __cnt];
}
function _each(obj, callback) {
for (var key in obj) {
if (hasOwnKey(obj, key)) callback(key, obj[key]);
}
}
function on(eventName, callback, context) {
return _bind(eventName, callback, 0, context);
}
function _fire_func(eventName, args) {
if (hasOwnKey(__onfireEvents, eventName)) {
_each(__onfireEvents[eventName], function(key, item) {
item[0].apply(item[2], args);
if (item[1]) delete __onfireEvents[eventName][key];
});
}
}
function fireSync(eventName) {
_fire_func(eventName, slice(arguments, 1));
}
return {
on: on,
fireSync: fireSync,
};
});
app.js中的应用
var signalR = require('utils/signalr.1.0.js');
可以去官网找:https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js
var senparcWebsocket = require('utils/websocket.js');
const onfire = require('/utils/onfire.js');
在app.js里面定义一个函数
socketConnection: function () {
let _this = this;
var hubUrl =
this.globalData.hubHost +
'/main/signalr-hubs/content-chat?token=' +
this.globalData.accessToken;
var onStart = function () {
console.log('ws started');
};
var onError = async function () {
if(!getNetworkType()){
let refreshToken = wx.getStorageSync('tokenData').refreshToken;
if(refreshToken) await updateToken.refreshHttp(refreshToken,this);
}
setTimeout(() => {
_this.socketConnection();
}, 2000);
};
senparcWebsocket.buildConnectionAndStart(
hubUrl,
signalR,
onStart,
onError,
this.globalData.stickyCookie
);
this.globalData.websocket = senparcWebsocket;
senparcWebsocket.onReceiveMessage('OnConnected', (res) => {
console.log('OnConnected连接成功');
if (this.globalData.onConnected) {
this.globalData.onConnected(res);
}
});
senparcWebsocket.onReceiveMessage('MessageCreated', (res) => {
onfire.fireSync('MessageCreated', res);
});
wx.onSocketOpen((res) => {
console.log('WebSocket 连接成功!');
});
wx.onSocketClose((res) => {
console.log('WebSocket 已关闭!');
setTimeout(() => {
this.socketConnection();
}, 1000);
});
wx.onSocketError((res) => {
console.log('WebSocket连接打开失败,请检查!');
setTimeout(() => {
this.socketConnection();
}, 5000);
});
},
页面中的使用inde.js
const onfire = require("../../utils/onfire.js")
var currentPage;
onfire.on('MessageCreated', (res) => {
if (currentPage) {
currentPage.handleReceiveMessage && currentPage.handleReceiveMessage(res);
}
});
Page({
onLoad(){},
onShow(){},
handleReceiveMessage(res){
console.log('接收消息-----')
}
})
|