Detailed use of SIGNALR technology in ASP.

Source: Internet
Author: User
This article mainly introduces the use of SIGNALR technology under the ASP., small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

First, preface

Last time we talked about how to use WebSocket in ASP. This time the protagonist is SIGNALR it provides us with a framework for simplifying operation WebSocket.

ASP. NET SignalR is an ASP-class library that enables real-time communication in ASP. What is the web of real-time communication? is to let the client (Web page) and the server side can notify each other messages and call methods, of course, this is real-time operation. WebSockets is a new API provided by HTML5, which allows you to establish a socket connection between Web pages and the server side, SIGNALR using WebSockets when WebSockets is available (ie, browser support HTML5). When not supported, SIGNALR will use other techniques to ensure that the same effect is achieved.

SIGNALR also offers a very simple and easy-to-use high-level API that allows the server side to invoke JavaScript functions on the client individually or in bulk, and makes it easy to manage connections, such as client connections to the server, or disconnection, client teaming, and client authorization. The use of SIGNALR is very easy to implement.

Ii. Current situation of SIGNALR

We know that SIGNALR is not included in the ASP. NET core 1.0.x version, but the SIGNALR technology program is integrated in the ASP. NET core 1.2 release. and its development team will use typescript to rewrite its JavaScript client, and the server side will be close to the way that ASP. NET core is developed, such as integration into the ASP. NET core Dependency Injection framework.

The current situation is that the SIGNALR technology cannot be used in 1.0, and the demo presented in this paper is done in 1.1.

Third, integrated SIGNALR

Of course, there is a period of time when ASP. NET Core 1.2 is not ready to be integrated signalr, we need to integrate SIGNALR manually.

To use SignalR in ASP. NET Core, first refer to the NuGet package for Microsoft.AspNetCore.SignalR.Server, Microsoft.AspNetCore.WebSockets.

Of course, the above also said that there is no ASP. NET core does not have integrated signalr, so nuget can not find SIGNALR package, want to add a reference we have to go to myget up to find.

1. Add a NuGet source

Create a new Nuget.config file in the program root directory as follows:

<?xml version= "0" encoding= "utf-8"?><configuration>  <packageSources>    <clear/>      <add key= "Aspnetcidev" value= "Https://dotnetmygetorg/F/aspnetcore-ci-dev/api/v3/indexjson"/>      < Add key= "apinugetorg" value= "Https://apinugetorg/v3/indexjson"/>  </packagesources></ Configuration>

Of course we can also refer to this assembly by setting the source of NuGet packages in Visual Studio.

2. Adding references in Project.json

"Microsoftaspnetcoresignalrserver": "0-*", "microsoftaspnetcorewebsockets": "0-*"

Note that the version of SIGNALR is the alpha version of 0.2.0, so the subsequent versions may also be larger! I heard it was a good rewrite.

It is important to note that SIGNALR is currently available only on ASP. NET Core 1.1 and above, and in this article I am using the version 1.0.0-preview2-003131. So referring to the problematic classmate can try to change the Coreapp version to 1.1, all Aspnetcore Assembly also changed to 1.1 version.

3. Add the Configuration Code

We need to add the following code to the Configureservices method in the Startup class:

public void Configureservices (iservicecollection services) {   servicesaddsignalr (options +    =     Optionshubsenabledetailederrors = true;   });}

Add the following code to the Configure method in the Startup class:

Appusewebsockets (); appusesignalr ();

4. Add a Hub class

Here we only implement a small demo, a simple chat room, many people can see their respective messages sent:

public class chathub:hub{public    static list<string> connectedusers;    public void Send (string originatoruser, String message)    {      clientsallmessagereceived (originatoruser, message) ;    }    public void Connect (string newuser)    {      if (connectedusers = = null)        connectedusers = new List<string> () ;      Connectedusersadd (newuser);      Clientscallergetconnectedusers (connectedusers);      Clientsothersnewuseradded (NewUser);    }}

5. Client Support

In the Wwwroot directory, create an HTML static file named Chat.html, which reads as follows:

<! DOCTYPE html>

Create a chat.js in the same directory add the script to implement the feature:

var userName = prompt ("Enter Your Name:"); var chat = $connectionchatHub; chatclientmessagereceived = function (Originatoru SER, message) {  $ ("#messages") Append (' <li><strong> ' + originatoruser + ' </strong>: ' + message);}; Chatclientgetconnectedusers = function (userlist) {for  (var i = 0; i < userlistlength; i++)    AddUser (userlist[i ]);}; chatclientnewuseradded = function (newuser) {  addUser (newuser);} $ ("#messageBox") focus (); $ ("#sendMessage") Click (function () {  chatserversend (userName, $ ("#messageBox") Val ());  $ ("#messageBox") Val ("");  $ ("#messageBox") focus ();}); $ ("#messageBox") KeyUp (function (event) {  if (Eventkeycode = =)    $ ("#sendMessage") Click ();}); function AddUser (user) {  $ ("#userList") Append (' <li> ' + user + ' </li> ');} $connectionhublogging = true; $connectionhubstart () Done (function () {  chatserverconnect (userName);});

Finally, let's run it:


The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.

Related Article

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.