在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
第一种:采用集线器类(Hub)+非自动生成代理模式: 服务端与客户端分别定义的相对应的方法,客户端通过代理对象调用服务端的方法,服务端通过IHubConnectionContext回调客户端的方法,客户端通过回调方法接收结果。 服务端代码: //StartUp.cs 采用OWIN启动方式 using System; using System.Threading.Tasks; using Microsoft.Owin; using Owin; using Microsoft.AspNet.SignalR; [assembly: OwinStartup(typeof(TestWebApp.Models.Startup))] namespace TestWebApp.Models { public class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } } //ChatHub类文件 using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Web; namespace TestWebApp.Models { [HubName("chat")] public class ChatHub : Hub { public static ConcurrentDictionary<string, string> OnLineUsers = new ConcurrentDictionary<string, string>(); [HubMethodName("send")] public void Send(string message) { string clientName = OnLineUsers[Context.ConnectionId]; message = HttpUtility.HtmlEncode(message).Replace("\r\n", "<br/>").Replace("\n", "<br/>"); Clients.All.receiveMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), clientName, message); } [HubMethodName("sendOne")] public void Send(string toUserId, string message) { string clientName = OnLineUsers[Context.ConnectionId]; message = HttpUtility.HtmlEncode(message).Replace("\r\n", "<br/>").Replace("\n", "<br/>"); Clients.Caller.receiveMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("您对 {1}", clientName, OnLineUsers[toUserId]), message); Clients.Client(toUserId).receiveMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("{0} 对您", clientName), message); } public override System.Threading.Tasks.Task OnConnected() { string clientName = Context.QueryString["clientName"].ToString(); OnLineUsers.AddOrUpdate(Context.ConnectionId, clientName, (key, value) => clientName); Clients.All.userChange(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), string.Format("{0} 加入了。", clientName), OnLineUsers.ToArray()); return base.OnConnected(); }
web端代码: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <meta charset="utf-8" /> <title>聊天室</title> <script src="~/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script> <script src="~/Scripts/jquery.signalR-2.2.0.min.js" type="text/javascript"></script> <style type="text/css"> #chatbox { width: 100%; height: 500px; border: 2px solid blue; padding: 5px; margin: 5px 0px; overflow-x: hidden; overflow-y: auto; } .linfo { } .rinfo { text-align: right; } </style> <script type="text/javascript"> $(function () { var clientName = $("#clientname").val(); var eChatBox = $("#chatbox"); var eUsers = $("#users"); var conn = $.hubConnection(); conn.qs = { "clientName": clientName }; conn.start().done(function () { $("#btnSend").click(function () { var toUserId = eUsers.val(); if (toUserId != "") { chat.invoke("sendOne", toUserId, $("#message").val()) .done(function () { //alert("发送成功!"); $("#message").val("").focus(); }) .fail(function (e) { alert(e); $("#message").focus(); }); } else { chat.invoke("send", $("#message").val()) .done(function () { //alert("发送成功!"); $("#message").val("").focus(); }) .fail(function (e) { alert(e); $("#message").focus(); }); } }); }); var chat = conn.createHubProxy("chat"); chat.on("receiveMessage", function (dt, cn, msg) { var clsName = "linfo"; if (cn == clientName || cn.indexOf("您对") >= 0) clsName = "rinfo"; eChatBox.append("<p class='" + clsName + "'>" + dt + " <strong>" + cn + "</strong> 说:<br/>" + msg + "</p>"); eChatBox.scrollTop(eChatBox[0].scrollHeight); }); 备注:服务端与客户端代码都比较简单,网上相关的说明也有,这里就不再解说了,只说一下这种方式JS端调用服务端方法采用:chat.invoke,而被服务端回调的方法则采用:chat.on (这里的chat是createHubProxy创建得来的) 第二种:采用集线器类(Hub)+自动生成代理模式 服务端代码:与第一种相同,无需改变。 web端代码: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <meta charset="utf-8" /> <title>聊天室</title> <script src="~/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script> <script src="~/Scripts/jquery.signalR-2.2.0.min.js" type="text/javascript"></script> <script src="~/signalr/hubs" type="text/javascript"></script> <style type="text/css"> #chatbox { width: 100%; height: 500px; border: 2px solid blue; padding: 5px; margin: 5px 0px; overflow-x: hidden; overflow-y: auto; } .linfo { } .rinfo { text-align: right; } </style> <script type="text/javascript"> $(function () { var clientName = $("#clientname").val(); var eChatBox = $("#chatbox"); var eUsers = $("#users"); var chat = $.connection.chat; $.connection.hub.qs = { "clientName": clientName }; chat.state.test = "test"; chat.client.receiveMessage = function (dt, cn, msg) { var clsName = "linfo"; if (cn == clientName || cn.indexOf("您对")>=0) clsName = "rinfo"; eChatBox.append("<p class='" + clsName + "'>" + dt + " <strong>" + cn + "</strong> 说:<br/>" + msg + "</p>"); eChatBox.scrollTop(eChatBox[0].scrollHeight); } chat.client.userChange = function (dt, msg, users) { eChatBox.append("<p>" + dt + " " + msg + "</p>"); eUsers.find("option[value!='']").remove(); for (var i = 0; i < users.length; i++ |
请发表评论