Simple Application of SignalR in ASP. net mvc, mvcsignalr

Source: Internet
Author: User

Simple Application of SignalR in ASP. net mvc, mvcsignalr

I. Introduction

ASP. NET SignalR is a library provided by ASP. NET developers. It simplifies the process for developers to add real-time Web functions to applications. The real-time Web function refers to a function that allows the server code to push content immediately when the connected client becomes available, rather than waiting for the server to wait for the client to request new data. -- Baidu encyclopedia

ASP. NET SignalR is a class library under ASP. NET. It can implement real-time communication in ASP. NET Web projects. Allows clients (Web pages) and servers to notify each other of messages and call methods.

SignalR automatically processes connection management, allowing the server to broadcast messages to all connected clients at the same time, such as chat rooms. You can also send messages to specific clients. The connection between the client and the server is persistent. Unlike the traditional HTTP connection, it is re-established for each communication.

SignalR supports the "server push" function. The server code can use Remote Procedure Call (RPC) to call the client code in the browser, instead of the Common Request Response Model on the network today.

In short,SignalR is an html websocket framework running on the. NET platform.The main purpose of this function is to enable the server to actively Push messages to the client page.

  Note:WebSocket requires the Server to use Windows Server 2012 or Windows 8 and. NET Framework 4.5. If the Server does not meet these requirements, SignalR will try to use other transmissions for connection.

Ii. Installation

Open the manage NuGet packages, search for SignalR, and install the following packages.


After the installation is complete, some references will be added to the program.

3. write code

Because SignalR2 is used, you need to create the Startup. cs class and configure the hub.

Using Microsoft. owin; using Owin; [assembly: OwinStartup (typeof (SignalRStartup. startup)] namespace SignalRStartup {public class Startup {public void Configuration (IAppBuilder app) {// configure the hub app. mapSignalR ();}}}

Then write the hub class of 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 the sendMessage method of all Clients (sendMessage has two 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 code

@ {ViewBag. title = "SignaIR chat window ";} <div class = "container"> <input type = "text" id = "message"/> <input type = "button" id = "sendmessage" value = "biubiu "/> <ul id = "messageBox"> </ul> </div> @ section scripts {<script src = "~ /Scripts/jquery. signalR-2.2.2.min.js "> </script> <script src = "~ /Signalr/hubs "> </script> <script> $ (function () {// reference the automatically generated hub proxy var chat =$. connection. serverHub; // defines the client sendMessage called by the server to display the new message chat. client. sendMessage = function (name, message) {// Add a message to the page $ ("# messageBox "). append ('<li> <strong style = "color: green">' + name + '</strong>:' + message + '</li> ');} // set the focus to the input box $ ('# message '). focus (); // start connecting to the server $. connection. hub. start (). done (function () {$ ('# sendmessage '). click (function () {// call the Send method chat of the server hub. server. sendMsg ($ ('# message '). val (); // clear the information in the input box and obtain the focus $ ("# message "). val (''). focus () ;})}); </script>}

Running Effect: Send a message in any window. All other clients can receive the message.

When running the program, the Web page establishes a connection with the SignalR service. The specific connection code is: $. connection. hub. start (). The purpose of this Code is to establish a connection with the SignalR service. The following done function indicates that a click event is registered for the button after the connection is established successfully. You can also use the hub object chat. connextion. start ()

Do you still remember this sentence?
<Script src = "~ /Signalr/hubs "> </script>
Result of F12

Clients. All. sendMessage in the demo above calls the sendMessage function of All Clients, which belongs to group sending.

The following is a demo of a client group.

Server code

Public void AddToRoom (string groupName, string userName) {// Add the connection to the specified group (Groups is the interface attribute in HubBase) Groups. add (Context. connectionId, groupName); // obtain the client group based on the group name and call the addUserIn method Clients of the group. group (groupName, new string [0]). addUserIn (groupName, userName);} public void Send (string groupName, string detail, string userName) {// Clients. all. addSomeMessage (detail); // send the message to all groups in batches. // call addSomeMessage Clients of a group of Clients. group (groupName, new string [0]). addSomeMessage (groupName, detail, userName );}

Client code

Chat. client. addSomeMessage = function (groupId, detail, userName) {lele.info ("broadcast message:" + detail); $ ("# contentMsg "). append ("<li>" + userName + ":" + detail + "</li>") ;}; chat. client. addUserIn = function (groupId, userName) {$ ("# contentMsg "). append ("<li>" + userName + "enter" + groupId + "chat room! </Li> ") ;};$. connection. hub. logging = true; // start the signalr status function $. connection. hub. start (). done (function () {// join the chat room $ ("# joinRoom "). click (function () {var groupId =$ ("# groupId "). val (); var userName = $ ("# userName "). val (); chat. server. addToRoom (groupId, userName) ;}); // send a message $ ("# send "). click (function () {var detail =$ ("# message "). val (); var groupId =$ ("# groupId "). val (); var userName = $ ("# userName "). val (); chat. server. send (groupId, detail, userName );});});

Running Effect


From the above two figures, we can see that the client implements grouping

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.