本文不對小程序與signalr做任何介紹,默認讀者已經掌握
SignalR沒有提供小程序使用的客戶端js,所以本人參考signlar.js寫了小程序版signalr-client.js 代碼開源,地址 https://github.com/liangshiw/SignalRMiniProgram-Client
先上效果圖
Install-Package Microsoft.AspNetCore.SignalR
現(xiàn)在就可以創(chuàng)建hub集線器了,首先定義一個類來描述已在線的用戶,它需要頭像和姓名
public class OnlineClient
{
public string NickName { get; set; }
public string Avatar { get; set; }
}
接下來我們在連接創(chuàng)建時,把當前用戶做為在線用戶添加到字典中,向該用戶發(fā)送加入成功的系統(tǒng)消息。并且同時向其他的用戶發(fā)送系統(tǒng)消息
public override async Task OnConnectedAsync()
{
var http = Context.GetHttpContext();
var client = new OnlineClient()
{
NickName = http.Request.Query["nickName"],
Avatar = http.Request.Query["avatar"]
};
lock (SyncObj)
{
OnlineClients[Context.ConnectionId] = client;
}
await base.OnConnectedAsync();
await Groups.AddToGroupAsync(Context.ConnectionId, ChatName);
await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("system", $"用戶{client.NickName}加入了群聊");
await Clients.Client(Context.ConnectionId).SendAsync("system", $"成功加入{ChatName}");
}
同樣在用戶斷開連接時做離線處理
public override async Task OnDisconnectedAsync(Exception exception)
{
await base.OnDisconnectedAsync(exception);
bool isRemoved;
OnlineClient client;
lock (SyncObj)
{
isRemoved = OnlineClients.TryRemove(Context.ConnectionId, out client);
}
await Groups.RemoveFromGroupAsync(Context.ConnectionId, ChatName);
if (isRemoved)
{
await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("system", $"用戶{client.NickName}退出了群聊");
}
}
下面就只有一個簡單的發(fā)送消息方法了,首先查看當前用戶是否在線并做相應處理,如果在線就把當前用戶的消息和頭像姓名一起發(fā)送給組中的其他客戶端
public async Task SendMessage(string msg)
{
var client = OnlineClients.Where(x => x.Key == Context.ConnectionId).Select(x=>x.Value).FirstOrDefault();
if (client == null)
{
await Clients.Client(Context.ConnectionId).SendAsync("system", "您已不在聊天室,請重新加入");
}
else
{
await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("receive", new { msg, nickName = client.NickName, avatar = client.Avatar });
}
}
在小程序中,我們需要在頁面加載事件中創(chuàng)建與signalr的連接,并且注冊system系統(tǒng)消息與receive用戶消息兩個方法以接收服務端發(fā)來的消息
onLoad: function (options) {
this.hubConnect = new Hub.HubConnection();
this.hubConnect.start("https://chat.jingshonline.net/chat", { nickName: app.globalData.userInfo.nickName, avatar: app.globalData.userInfo.avatarUrl });
this.hubConnect.onOpen = res => {
console.log("成功開啟連接")
}
this.hubConnect.on("system", res => {
wx.showModal({
title: '系統(tǒng)消息',
content: res,
})
})
this.hubConnect.on("receive", res => {
centendata.push({
content: res.msg,
time: new Date().toLocaleString(),
head_owner: res.avatar,
is_show_right: 0
});
this.setData({
centendata: centendata
})
})
}
同樣在頁面銷毀時應斷開與signalr服務器的連接
onUnload: function () {
this.hubConnect.close({ reason: "退出" })
}
發(fā)送方法也非常簡單,只需要調用sendMessage方法并把用戶輸入的消息傳入就大功告成了,其它就是頁面上的處理了
this.hubConnect.send("sendMessage",message);
完整的代碼請去github https://github.com/liangshiw/SignalRMiniProgram-Client/tree/master/sample
需要注意的是在打開小程序代碼時,請修改project.config.json文件中的appid,如果項目不錯的話還請大家加個星,順便再follow一下本人