微信小程序與aspnetcore signalr實例
本文不對小程序與signalr做任何介紹,默認讀者已經掌握
寫在之前
SignalR沒有提供小程序使用的客戶端js,所以本人參考signlar.js寫了小程序版signalr-client.js 代碼開源,地址 https://github.com/liangshiw/SignalRMiniProgram-Client
先上效果圖


開始編碼
首先需要創建一個aspnetcore的mvc項目,創建完成后我們需要安裝signalr的包
Install-Package Microsoft.AspNetCore.SignalR
現在就可以創建hub集線器了,首先定義一個類來描述已在線的用戶,它需要頭像和姓名
public class OnlineClient
{
public string NickName { get; set; }
public string Avatar { get; set; }
}
接下來我們在連接創建時,把當前用戶做為在線用戶添加到字典中,向該用戶發送加入成功的系統消息。並且同時向其他的用戶發送系統消息
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}退出了群聊");
}
}
下面就只有一個簡單的發送消息方法了,首先查看當前用戶是否在線並做相應處理,如果在線就把當前用戶的消息和頭像姓名一起發送給組中的其他客戶端
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 });
}
}
在小程序中,我們需要在頁面加載事件中創建與signalr的連接,並且注冊system系統消息與receive用戶消息兩個方法以接收服務端發來的消息
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: '系統消息',
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: "退出" })
}
發送方法也非常簡單,只需要調用sendMessage方法並把用戶輸入的消息傳入就大功告成了,其它就是頁面上的處理了
this.hubConnect.send("sendMessage",message);
完整的代碼請去github https://github.com/liangshiw/SignalRMiniProgram-Client/tree/master/sample
需要注意的是在打開小程序代碼時,請修改project.config.json文件中的appid,如果項目不錯的話還請大家加個星,順便再follow一下本人