SignalR
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SignalR相关的知识,希望对你有一定的参考价值。
http://blog.csdn.net/kesalin/article/details/8166925
打开 NuGet 的 package manager console(Tools->Library package manager),输入:install-package SignalR.Sample,回车安装
后台:
using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using Microsoft.Owin.Cors; using Microsoft.Owin.Hosting; using Owin; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SignalRBackService { class Program { static void Main(string[] args) { string url = "http://192.168.2.171:8181"; using (WebApp.Start(url)) { Console.WriteLine("Server running on {0}", url); Console.ReadLine(); } } } public class Startup { public void Configuration(IAppBuilder app) { app.Map("/signalr", map => { // Setup the cors middleware to run before SignalR. // By default this will allow all origins. You can // configure the set of origins and/or http verbs by // providing a cors options with a different policy. map.UseCors(CorsOptions.AllowAll); var hubConfiguration = new HubConfiguration { // You can enable JSONP by uncommenting line below. // JSONP requests are insecure but some older browsers (and some // versions of IE) require JSONP to work cross domain // EnableJSONP = true //EnableJSONP = true, //EnableDetailedErrors = true, //EnablejavascriptProxies = true }; // Run the SignalR pipeline. We‘re not using MapSignalR // since this branch is already runs under the "/signalr" // path. map.RunSignalR(hubConfiguration); }); } } [HubName("myHub")] public class MyHub : Hub { public void Send(string group, string recipient, string name, string message) { // IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MyHub>(); var dd = Context.ConnectionId; #region 单个人 //if (!string.IsNullOrEmpty(recipient)) //{ // //单个人 // Clients.Client(recipient).addMessage(name, message); //} //else //{ // //全部 // Console.WriteLine(message); // Clients.All.addMessage(name, message); //} #endregion #region 群组 if (!string.IsNullOrEmpty(group)) { var ids = group.Split(‘,‘); foreach (var id in ids) { Groups.Add(id, "测试组"); } Clients.Group("测试组").addMessage(name, message); } #endregion //var toSelfinfo = "You had sent message " + message; //Caller.addSomeMessage(clientName, toSelfinfo); //// Call the addMessage method on all clients //Clients.addSomeMessage(clientName, message); //Clients[Context.ConnectionId].addSomeMessage(name, message); } } }
前端:
<!DOCTYPE html> <html> <head> <title>SignalR Simple Chat</title> <style type="text/css"> .container { background-color: #99CCFF; border: thick solid #808080; padding: 20px; margin: 20px; } </style> </head> <body> <div class="container"> 消息:<input type="text" id="message" /> 接收者:<input type="text" id="recipientId" /> 群组:<input type="text" id="groupId" /> <input type="button" id="sendmessage" value="Send" /> <input type="hidden" id="displayname" /> <ul id="discussion"></ul> </div> <!--Script references. --> <!--Reference the jQuery library. --> <script src="Scripts/jquery-1.8.2.min.js"></script> <!--Reference the SignalR library. --> <script src="Scripts/jquery.signalR-2.1.1.min.js"></script> <!--Reference the autogenerated SignalR hub script. --> <script src="http://192.168.2.171:8181/signalr/hubs"></script> <!--Add script to update the page and send messages.--> <script type="text/javascript"> $(function () { //Set the hubs URL for the connection $.connection.hub.url = "http://192.168.2.171:8181/signalr"; for(var i in $.connection){ console.log(i+":"+$.connection) } // Declare a proxy to reference the hub. var chat = $.connection.myHub; // Create a function that the hub can call to broadcast messages. chat.client.addMessage = function (name, message) { alert(message); // Html encode display name and message. //var encodedName = $(‘<div />‘).text(name).html(); //var encodedMsg = $(‘<div />‘).text(message).html(); // Add the message to the page. //$(‘#discussion‘).append(‘<li><strong>‘ + encodedName // + ‘</strong>: ‘ + encodedMsg + ‘</li>‘); }; // Get the user name and store it to prepend to messages. $(‘#displayname‘).val(prompt(‘Enter your name:‘, ‘‘)); // Set initial focus to message input box. $(‘#message‘).focus(); // Start the connection. $.connection.hub.start().done(function () { $(‘#sendmessage‘).click(function () { // Call the Send method on the hub. chat.server.send($(‘#groupId‘).val(),$(‘#recipientId‘).val(), $(‘#displayname‘).val(), $(‘#message‘).val()); // Clear text box and reset focus for next comment. $(‘#message‘).val(‘‘).focus(); }); }); }); </script> </body> </html>
以上是关于SignalR的主要内容,如果未能解决你的问题,请参考以下文章
SignalR OnConnected 与多台服务器和 Redis 背板
角度 SignalR 经常断开连接并显示错误状态代码 1006
websocket握手代码期间无法连接signalR错误:400