This article mainly introduces the simple application of SIGNALR in ASP. NET MVC, it has certain reference value, the interested small partners can refer to
First, Introduction
The ASP. NET SignalR is a library for ASP. NET developers that simplifies the process of adding real-time WEB functionality to applications by developers. Real-time WEB functionality refers to the ability for server code to push content immediately when a connected client becomes available, rather than having the server wait for the client to request new data. --Baidu Encyclopedia
First, the ASP. NET SignalR is a class library that enables real-time communication in ASP. NET Web projects. Let the client (Web page) and the server side can notify each other of messages and invoke methods.
SIGNALR automatically handles connection management, allowing the server to broadcast messages to all connected clients at the same time, such as chat rooms. You can also send a message to a specific client. The connection between the client and the server is persistent, unlike the traditional HTTP connection, which is re-established for each communication.
SIGNALR supports the server push feature, where server code can invoke client code in the browser using remote procedure call (RPC) instead of the request response model that is common today on the network.
In summary,SIGNALR is an HTML WebSocket framework that runs on the. NET platform , and its main purpose is to implement server proactive push (push) messages to client pages
Note: WebSocket requires the server to use Windows Server 2012 or Windows 8 and. NET Framework 4.5 If these requirements are not met, SIGNALR will attempt to connect using a different transport
Second, installation
Open the Manage NuGet package, search for SIGNALR, install the following packages
There are some more references in the program after the installation is complete
Third, write the code
Because SignalR2 is used, you need to create a new Startup.cs class, configure the hub, and write the following
Using microsoft.owin;using Owin; [Assembly:owinstartup (typeof (Signalrstartup.startup))]namespace signalrstartup{public class Startup { Public void Configuration (Iappbuilder app) { //configure Hub app. MAPSIGNALR ();}}}
Then write the hub class on the server
Using system;using system.collections.generic;using system.linq;using system.threading.tasks;using System.Web;using Microsoft.aspnet.signalr;namespace signalr{public class Serverhub:hub {public void sendmsg (string Message) { //Call all client's SendMessage method (SendMessage has 2 parameters) Clients.All.sendMessage (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss"), message);}}}
Create Homocontroller and its action function index
Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Mvc;namespace signalr.controllers{public class Homecontroller:controller {public actionresult Index () { return View ();}} }
Index Front segment Code
@{viewbag.title = "signair chat window";} <p class= "container" > <input type= "text" id= "message"/> <input t Ype= "button" id= "SendMessage" value= "Biubiu"/> <ul id= "MessageBox" ></ul> </p> @section Scripts { <script src= "~/scripts/jquery.signalr-2.2.2.min.js" ></script> <script src= "~/signalr/hubs" >< /script> <script> $ (function () {//reference auto-generated hub agent var chat = $.connection.serverhub; Defines the client sendMessage of the server call to display a new message Chat.client.sendMessage = function (name, message) {//Add message to page $ ("#messageBox"). Append (' <li><strong style= ' color:green ' > ' +name+ ' </strong>: ' +message+ ' </li > '); }//Set focus to the input box $ (' #message '). focus (); Start connecting to Server $.connection.hub.start (). Done (function () {$ (' #sendmessage '). Click (function () {//Call service The Send Method CHAT.SERVER.SENDMSG ($ (' #message ') of the Terminal hub. Val ()); Empty input box information and get focus$ ("#message"). Val ("). focus (); }) }) }); </script>}
Run the effect, send a message in either window, and all other clients can receive the message.
When running the program, the Web page is connected to the SIGNALR service, and the specific code for establishing the connection is: $.connection.hub.start (). The function of this code is to establish a connection with the SIGNALR service, after which the done function indicates that a click event is registered for the button after the connection is established, or the hub object can be used Chat.connextion.start ()
Do you remember this sentence?
<script src= "~/signalr/hubs" ></script>
F12 See the results
The Clients.All.sendMessage in the above demo is called the SendMessage function of all clients, belonging to the mass.
Here is a demo of a client group
Service-side code
public void Addtoroom (string groupName, String userName) { //Adds a connection to the specified group (groups as an interface property in Hubbase) Groups.add (Context.connectionid, groupName); Gets the group of the corresponding client based on the group name, calling the group's Adduserin method Clients.group (GroupName, New string[0]). Adduserin (GroupName, userName); } public void Send (string groupName, string detail, string userName) { //clients.all.addsomemessage (detail);// the Addsomemessage clients.group (groupName, New string[0]) is sent to all//calls to a certain group of clients. Addsomemessage (GroupName, Detail, userName); }
Client code
Chat.client.addSomeMessage = function (groupId, detail, userName) { console.info ("Broadcast message:" + detail); $ ("#contentMsg"). Append ("<li>" + UserName + ":" + detail + "</li>"); }; Chat.client.addUserIn = function (GroupId, userName) { $ ("#contentMsg"). Append ("<li>" + userName + "enter" + groupid+ "Number chat room! </li> "); }; $.connection.hub.logging = true; Start the SIGNALR status feature $.connection.hub.start (). Done (function () { //join chat room $ ("#joinRoom"). Click (function () { var groupId = $ ("#groupId"). Val (); var userName = $ ("#userName"). Val (); Chat.server.addToRoom (GroupId, userName); }); Send Message $ ("#send"). Click (function () { var detail = $ ("#message"). Val (); var groupId = $ ("#groupId"). Val (); var userName = $ ("#userName"). Val (); Chat.server.send (groupId, detail, userName); }) ;
Run effect
As can be seen from the above two graphs, the client implements the grouping