簡單的實現了廣播和私聊;下面是效果圖:
實現過程:
首先通過NeGet 在項目中安裝Signalr
然后在文件App_Start 下面添加一個啟動類=>Startup;並且在Web.config 里面添加配置
using Microsoft.Owin; using Owin; [assembly: OwinStartup(typeof(WebApplication.Startup))] namespace WebApplication { public class Startup { public void Configuration(IAppBuilder app) { // Any connection or hub wire up and configuration should go here app.MapSignalR(); } } }
<appSettings> <!--<add key="owin:AppStartup" value="WebApplication.Startup" />--> <add key="owin:AutomaticAppStartup" value="true" /> </appSettings>
到這里准備工作就完成了; 這里的 Startup.cs 和 Web.config里面的配置 有點麻煩 第一次實現沒有經驗 導致后面代碼總是沒有生成前台頁面的引用【~/signalr/hubs】,導致運行以后報404錯誤;
他們的關系是這樣的
具體地址:http://www.voidcn.com/article/p-rzbdznjc-byu.html
實現代碼:
后台代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; namespace WebApplication { [HubName("ChatRoomHub")] public class SignalR : Hub { static List<UserEntity> users = new List<UserEntity>(); /// <summary> /// 添加用戶 /// </summary> /// <param name="nickName"></param> public void UserEnter(string nickName) { UserEntity userEntity = new UserEntity { NickName = nickName, ConnectionId = Context.ConnectionId }; users.Add(userEntity); Clients.All.NotifyUserEnter(nickName, users);//調用前台NotifyUserEnter方法 } List<string> userIdList = new List<string>(); /// <summary> /// 發送消息 /// </summary> /// <param name="nickName"></param> /// <param name="message"></param> /// <param name="selectUserId"></param> public void SendMessage(string nickName, string message, string selectUserId) { if (!string.IsNullOrEmpty(selectUserId)) { userIdList = selectUserId.Split(',').ToList(); foreach (string str in userIdList) { if (users.Any(c => c.ConnectionId == str)) { //只發送用戶選中的group //Clients.Group(str, new string[0]).NotifySendMessage(nickName, message); Clients.Client(str).NotifySendMessage(nickName, message); } } } else { Clients.All.NotifySendMessage(nickName, message);//調用前台NotifySendMessage方法 } } } public class UserEntity { public string NickName { get; set; } public string ConnectionId { get; set; } } }
前台代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="Scripts/jquery-3.3.1.min.js"></script> <script src="Scripts/jquery.signalR-2.4.1.min.js"></script> <script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script> </head> <body> <label>在線人數:</label><span id="rs">0</span><br /> <input type="text" id="name" /> <input type="button" id="dl" value="登錄" /><br /> <select id="mb"> <option value="">請選擇</option> </select> <input type="text" id="val" /> <input type="button" id="fs" value="發送" /> <br /> <div id="lt"> </div> <script> var chat; $(function () {
chat = $.connection.ChatRoomHub; //添加用戶 chat.client.NotifyUserEnter = function (nickName, users) { buildUserTemplate(nickName, users); } //用戶離開 chat.client.NotifyUserLeft = function (nickName, users) { buildUserTemplate(nickName, users); } chat.client.NotifySendMessage = function (nickName, message) { NotifySendMessage(nickName, message) } //用戶列表 function buildUserTemplate(nickName, users) { $("#rs").text(users.length); $("#mb").empty(); var txt = '<option value="">請選擇</option>'; $.each(users, function (e, v) { txt += '<option value="' + v.ConnectionId + '">' + v.NickName + '</option>'; }); $("#mb").append(txt); } function NotifySendMessage(nickName, message) { var txt = '<label>' + nickName + ':</label><span id="rs">' + message + '</span><br />'; $("#lt").append(txt); } }) var NameUser; $("#dl").click(function () { var name = $("#name").val(); NameUser = name; $.connection.hub.start().done(function () { chat.server.userEnter(name); }); }) $("#fs").click(function () { var nameId = $("#mb").val(); var txt = $("#val").val(); chat.server.sendMessage(NameUser, txt, nameId); }) </script> </body> </html>
頁面就是引用:<%: ResolveClientUrl("~/signalr/hubs") %> 就是前面說的報404 錯誤的地方 引用有風險 配置需謹慎!!!
1. js定義后台調用方法 chat.client.方法名=function(){} 這樣定義的方法在后台里面可以用 Clients.屬性.方法名()的方式調用 這里的屬性有
All 就是廣播;Client就是單個推送;其他的沒有嘗試。
2.js調用后台定義的方法:$.connection.ChatRoomHub.server.方法名(),【ChatRoomHub】 便是后台代碼里面的“HubName”; 上面將 $.connection.ChatRoomHub 賦值給了chat, 另外js調用后台方法名時首字母小寫 列:chat.server.userEnter(name) 不然會找不到方法
3. $.connection.hub.start().done(function () { chat.server.userEnter(name); }); 這個方法應該是連接的意思吧;有時間了試一下 ;
暫時就寫到這里;
參考文檔: https://www.cnblogs.com/cang12138/p/7404124.html
這里寫的比我好可以去看看;