. net core 3.0 signalr – 03 compress transport content with messagepack

Time:2019-12-29

Basic introduction to messagepack

By default, signalr uses JSON to transfer data, but signalr provides flexible extension, supports message pack to serialize data, so as to increase performance, reduce network transmission effect and greatly improve response speed.

First, let’s look at an example of message pack custom serialization. Take a custom entity object as an example. You can use messagepackobject to mark the serialized object, and define the attribute name as the key (case sensitive), ignore a certain attribute, and define the custom key

[MessagePackObject(keyAsPropertyName: true)]
  public class OffLineData
  {
      /// <summary>
      // / user Id
      /// </summary>
      public string UserId { set; get; }
      /// <summary>
      // / connect Id
      /// </summary>
      public string ConnectionId { set; get; }
      /// <summary>
      ///Is this user's last connection
      /// </summary>
      public bool IsLast { set; get; }
      [IgnoreMember]
      public string Test { set;get;}
  }

  //For example, the new offlinedata() {userid = "1000", connectionid = "azdefasdfasdf", islast: true} should be {userid: "1000", connectionid: "azdefasdfasdf", islast: true} after being serialized through messagepack, which is basically the same as common JSON

At the same time, the message pack can also be defined in the form of array. The code is as follows

[MessagePackObject]
  public class OffLineData
    {
        /// <summary>
        // / user Id
        /// </summary>
        [Key(0)]
        public string UserId { set; get; }
        /// <summary>
        // / connect Id
        /// </summary>
        [Key(0)]
        public string ConnectionId { set; get; }
        /// <summary>
        ///Is this user's last connection
        /// </summary>
        [Key(0)]
        public bool IsLast { set; get; }
    }

  //For example, the new offlinedata() {userid = "1000", connectionid = "azdefasdfasdf", islast: true} serialized through messagepack should be ["10000", "azdefasdfasdf", true]

More content of message pack can end by itself, which will not be covered here

Add message pack support for signalr

  • Import the nuget package needed

Microsoft.AspNetCore.SignalR.Protocols.MessagePack

  • Modify previous configureservices

    //Add signalr
      services.AddSignalR(config =>
      {
          if (_webEnv.IsDevelopment())
          {
              config.EnableDetailedErrors = true;
          }
      })
      //Message pack support
      .AddMessagePackProtocol();
  • Introduction of messagepack parsing library in the front end

Because the message pack is transmitted in binary form, which reduces the bandwidth, but also increases the complexity of the code. Originally, the data can be used directly. Now we need to convert the binary data into normal data first. Fortunately, the official provides the corresponding JS librarymsgpack5signalr-protocol-msgpack
You can install it through the package management tool of vs or NPM, and then copy the required files to the Lib folder of the project. For example, my structure is

  signalr-protocol-msgpack
  |-msgpack5.js
  |-msgpack5.min.js
  |-signalr-protocol-msgpack.js
  |-signalr-protocol-msgpack.min.js

The front-end page introduces these two JSS (note the order: signal R, msgpack5, signal protocol msgpack)

  • Modify JS connection object to support message pack

    new signalR.HubConnectionBuilder()
      . configurelogging (signr. Loglevel. Error) // the log level of the front-end console. Configure as needed
      . withurl ('http: // localhost: 50001 / notify hub ') // the connection address, which is the address of the signr project
      . withhubprotocol (New signalr. Protocols. Msgpack. Messagepackhubprotocol()) // use messagepack to parse the pushed data
      . withautomaticreconnect ([0, 2000, 5000, 10000, 20000]) // configure the reconnection time
      .build();
    
      //Triggered when reconnected
      connection.onreconnecting(function (info) {
          console.info('----------------------------------signalr-- onreconnecting', info);
      });
    
      //Connection closed callback
      connection.onclose(function (err) {
          console.info('--------------------------------signalr-- onclose', err);
      });
    
      connection.start().then(function (data) {
          Console.log ('successfully connected to the signalr server ')
      }).catch(function (error) {
          console.error(error.toString());
      });

Unresolved issues

It is found that the object obtained through json.net serialization is directly delivered to messagepack serialization, and an error will be reported. No solution is found. It is directly changed to string transmission, and then it is parsed in the front end. Anyone who has met with it is welcome to give advice

At this point, the introduction of messagepack is over. For more information, please check the next one through quick navigation

Fast navigation

Title content
Indexes . net core 3.0 signalr – implement a business push system
Last article . net core 3.0 signalr – 02 use strongly typed hub
Next article . net core 3.0 signalr – 04 uses redis as the backplane to support horizontal expansion
Source address Source code
Official documents Official documents
MessagePack-CSharp MessagePack-CSharp
MessagePack MessagePack

. net core 3.0 signalr - 03 compress transport content with messagepack

Recommended Today

Build HTTP service with C + + Mongoose

Mongoose source code address:https://github.com/cesanta/mo… Mongoose user manual:https://www.cesanta.com/devel… Mngoose set up HTTP service #include <string> #include “mongoose.h” using namespace std; static const char *s_http_port = “8000”; static void ev_handler(mg_connection *nc, int ev, void *ev_data) { struct http_message *hm = (struct http_message *) ev_data; if (ev == MG_EV_HTTP_REQUEST) { std::string uri; if (hm->uri.p && hm->uri.p[0] == ‘/’) […]