Use SignalR technology and coresignalr in ASP. NET Core

Source: Internet
Author: User

Use SignalR technology and coresignalr in ASP. NET Core

I. Preface

Last time we talked about how to use WebSocket in ASP. NET Core. The main character of this time is SignalR, which provides us with a framework to simplify WebSocket operations.

ASP. NET SignalR is a class library under ASP. NET. It can implement real-time communication in ASP. NET Web projects. What is real-time communication Web? This means that the client (Web page) and the server can notify each other of messages and call methods. Of course, this is a real-time operation. WebSockets is a new API provided by HTML5. It can establish a Socket connection between the Web page and the server. When WebSockets is available (that is, the browser supports Html5) SignalR uses WebSockets, if it is not supported, SignalR will use other technologies to ensure the same effect.

SignalR also provides easy-to-use high-level APIs so that the server can call JavaScript Functions on the client in a single or batch and conveniently manage connections. For example, the client can connect to the server, it is easy to use SignalR to disconnect the connection, group the client, and authorize the client.

Ii. Current Situation of SignalR

We know that in ASP. NET Core 1.0.x does not contain SignalR, but the SignalR technical plan is integrated in ASP. NET Core 1.2, and its development team also needs to use TypeScript to rewrite its javascript client, and the server side will be close to ASP.. NET Core development method. For example, it will be integrated into ASP.. NET Core dependency injection framework.

The current situation is that SignalR technology cannot be used in 1.0. The demos implemented in this article are all carried out in 1.1.

3. Integrate SignalR

Of course, ASP. NET Core 1.2 has been released for some time. Currently, it is not a ready-made solution to integrate SignalR. We need to integrate SignalR manually.

To use SignalR in ASP. NET Core, you must first reference the NuGet Package of Microsoft. AspNetCore. SignalR. Server and Microsoft. AspNetCore. WebSockets.

Of course, as mentioned above, no ASP. NET Core is integrated with SignalR, so the SignalR package cannot be found on NUGET. If you want to add a reference, you have to go to MyGet to find it.

1. Add NuGet Source

Create a new file named NuGet. Config in the root directory of the program. The content of the file is 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 reference this Assembly by setting the NuGet Packages source in Visual Studio.

2. Add reference in project. json

"MicrosoftAspNetCoreSignalRServer": "0-*","MicrosoftAspNetCoreWebSockets": "0-*"

It can be noted that the SignalR version is 0.2.0 alpha version, so the subsequent version may change a lot! I heard it is a good rewrite.

It is worth noting that SignalR can only be used in ASP.. NET Core 1.1 or later. NET Core SDK version is 1.0.0-preview2-003131, so reference problematic students can try to change CoreApp version to 1.1, all AspNetCore Assembly also changed to 1.1 version.

3. Add configuration code

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, multiple people can access to view their respective messages:

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

Create an Html static file named chat.html under the wwwrootdirectory. The content is as follows:

<!DOCTYPE html>

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

var userName = prompt("Enter your name: ");var chat = $connectionchatHub;chatclientmessageReceived = function (originatorUser, 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 == 13)    $("#sendMessage")click();});function addUser(user){  $("#userList")append('<li>' + user + '</li>');}$connectionhublogging = true;$connectionhubstart()done(function () {  chatserverconnect(userName);});

Finally, let's run it:

Iv. Final

Attaches an available Demo: http://xiazai.jb51.net/201702/yuanma/AspNetCore.SignalRDemo_jb51.rar

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

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.