本文不對(duì)小程序與signalr做任何介紹,默認(rèn)讀者已經(jīng)掌握
aspnetcore Signalr文檔
小程序文檔
SignalR沒(méi)有提供小程序使用的客戶端js,所以本人參考signlar.js寫(xiě)了小程序版signalr-client.js 代碼開(kāi)源,地址 https://github.com/liangshiw/SignalRMiniProgram-Client
先上效果圖
Install-Package Microsoft.AspNetCore.SignalR
現(xiàn)在就可以創(chuàng)建hub集線器了,首先定義一個(gè)類來(lái)描述已在線的用戶,它需要頭像和姓名
public class OnlineClient { public string NickName { get; set; } public string Avatar { get; set; } }
接下來(lái)我們?cè)谶B接創(chuàng)建時(shí),把當(dāng)前用戶做為在線用戶添加到字典中,向該用戶發(fā)送加入成功的系統(tǒng)消息。并且同時(shí)向其他的用戶發(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}"); }
同樣在用戶斷開(kāi)連接時(shí)做離線處理
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}退出了群聊"); } }
下面就只有一個(gè)簡(jiǎn)單的發(fā)送消息方法了,首先查看當(dāng)前用戶是否在線并做相應(yīng)處理,如果在線就把當(dāng)前用戶的消息和頭像姓名一起發(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", "您已不在聊天室,請(qǐng)重新加入"); } else { await Clients.GroupExcept(ChatName, new[] { Context.ConnectionId }).SendAsync("receive", new { msg, nickName = client.NickName, avatar = client.Avatar }); } }
在小程序中,我們需要在頁(yè)面加載事件中創(chuàng)建與signalr的連接,并且注冊(cè)system系統(tǒng)消息與receive用戶消息兩個(gè)方法以接收服務(wù)端發(fā)來(lái)的消息
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("成功開(kāi)啟連接") } 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 }) }) }
同樣在頁(yè)面銷毀時(shí)應(yīng)斷開(kāi)與signalr服務(wù)器的連接
onUnload: function () { this.hubConnect.close({ reason: "退出" }) }
發(fā)送方法也非常簡(jiǎn)單,只需要調(diào)用sendMessage方法并把用戶輸入的消息傳入就大功告成了,其它就是頁(yè)面上的處理了
this.hubConnect.send("sendMessage",message);
需要注意的是在打開(kāi)小程序代碼時(shí),請(qǐng)修改project.config.json文件中的appid,如果項(xiàng)目不錯(cuò)的話還請(qǐng)大家follow一下本人
工作日 8:30-12:00 14:30-18:00
周六及部分節(jié)假日提供值班服務(wù)