Detailed explanation of using SignalR technology under ASP.NET Core

高洛峰
Release: 2017-02-10 17:35:44
Original
2176 people have browsed it

This article mainly introduces the use of SignalR technology under ASP.NET Core. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look

1. Preface

Last time we talked about how to use ASP.NET Core Use WebSocket in . The protagonist this time is SignalR, which provides us with a framework to simplify the operation of WebSocket.

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

SignalR of course also provides a very simple and easy-to-use high-level API, which allows the server to call JavaScript functions on the client individually or in batches, and it is very convenient to perform connection management, such as the client connecting to the server. , or disconnection, client grouping, and client authorization are all very easy to implement using SignalR.

2. Current situation of SignalR

We know that SignalR is not included in the ASP.NET Core 1.0.x version, but the SignalR technology plan It is integrated into ASP.NET Core version 1.2, and its development team will also use TypeScript to rewrite its javascript client. The server side will also be close to the development method of ASP.NET Core, 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 Demo implemented in this article is all conducted under 1.1.

3. Integrate SignalR

Of course, ASP.NET Core 1.2 is still some time away from its official release, and currently it is not ready to integrate SignalR. Solution, 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, there is currently no ASP.NET Core that does not integrate SignalR, so the SignalR package cannot be found on NUGET. If we want to add a reference, we have to go to MyGet to find it.

1. Add NuGet source

Create a new file named NuGet.Config in the program root directory with the following content:

<?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>
Copy after login

Of course we can also reference this assembly by setting the source of NuGet Packages in Visual Studio.

2. Add a reference to project.json

"MicrosoftAspNetCoreSignalRServer": "0-*",
"MicrosoftAspNetCoreWebSockets": "0-*"
Copy after login

You can notice that the version of SignalR is 0.2.0 Alpha version, so subsequent versions may change a lot! I heard it's easy to rewrite.

It is worth noting that SignalR is currently only available on ASP.NET Core 1.1 and above. The .NET Core SDK version I used in this article is 1.0.0-preview2-003131, so I quote Students who have problems can try to change the CoreApp version to 1.1, and all AspNetCore assemblies are also changed to version 1.1.

3. Add configuration code

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

public void ConfigureServices(IServiceCollection services)
{
   servicesAddSignalR(options => 
   {
     optionsHubsEnableDetailedErrors = true;
   });
}
Copy after login

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

appUseWebSockets();
appUseSignalR();
Copy after login

4. Add a HUB class

Here we only implement a small Demo, a simple chat room. Multiple people can see the messages sent by them when entering:

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);
    }
}
Copy after login

5. Client support

Create an Html static file named chat.html in the wwwroot directory with the following content:

<!DOCTYPE html>
<html>
<head>
  <title>Awesome Chat Application</title>
  <meta charset="utf-8" />
</head>
<body>
  <style type="text/css">
    userListp{ float: right; }
  </style>
  <ul id="messages"></ul>
  <input type="text" id="messageBox" />
  <input type="button" id="sendMessage" value="Send Message!" />
  <p class="userListp">
    <ul id="userList"> </ul>
  </p>
 
  <script src="http://ajaxaspnetcdncom/ajax/jQuery/jquery-minjs"></script>
  <script src="http://ajaxaspnetcdncom/ajax/signalr/jquerysignalr-minjs"></script>
  <script src="signalr/hubs"></script>
  <script src="chatjs"></script>
</body>
</html>
Copy after login

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

var userName = prompt("Enter your name: ");
var chat = $connectionchatHub;
chatclientmessageReceived = function (originatorUser, message) {
  $("#messages")append(&#39;<li><strong>&#39; + originatorUser + &#39;</strong>: &#39; + 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(&#39;<li>&#39; + user + &#39;</li>&#39;);
}
$connectionhublogging = true;
$connectionhubstart()done(function () {
  chatserverconnect(userName);
});
Copy after login

Finally let’s run it:

详解在ASP.NET Core下使用SignalR技术


The above is the entire content of this article. I hope it will be helpful to everyone's learning, and I also hope that everyone will support the PHP Chinese website.

For more detailed information on using SignalR technology under ASP.NET Core, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!