It's like JSON.
but fast and small.MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves.
默認我們在 ASP.NET Core SignalR 中使用 WebSocket 協議通信,默認使用 JSON 格式數據傳輸,為了更高效我們可以使用 MessagePack 來替換。 MessagePack 是一個高效的二進制序列化格式。它讓你像JSON一樣可以在各種語言之間交換數據。但是它比JSON更快、更小。小的整數會被編碼成一個字節,短的字符串僅僅只需要比它的長度多一字節的大小。
在 SignalR 中使用 MessagePack 也很簡單:
public void ConfigureServices(IServiceCollection services) { //自定義配置 services.Configure<DbSetting>(Configuration.GetSection("ConnectionStrings")); //https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-2.1 services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); //添加 Hangfire 服務 services.AddHangfire(config => config.UseRedisStorage(Redis)); // services.AddHangfire(config => config.UseSqlServerStorage("<connection string>")); //添加 Cookie 中間件 services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; // sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) //.AddAzureAdB2C(opts => Configuration.Bind("AzureAdB2C", opts)) .AddCookie(opts => { opts.LoginPath = new PathString("/account/login"); opts.AccessDeniedPath = new PathString("/account/denied"); }); services.AddSignalR(options => { //Faster pings for testing //options.KeepAliveInterval = TimeSpan.FromSeconds(5); }) .AddMessagePackProtocol(options => { // options.FormatterResolvers = new List<MessagePack.IFormatterResolver>() //{ // MessagePack.Resolvers.StandardResolver.Instance //}; }) .AddRedis(Configuration.GetConnectionString("Redis")); //返回大小寫問題 services.AddMvc() .AddJsonOptions(option => option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver()); }
.NET 客戶端
var hubConnection = new HubConnectionBuilder() .WithUrl("/chatHub") .AddMessagePackProtocol() .Build();
JavaScript 客戶端
npm install @aspnet/signalr-protocol-msgpack
<script src="~/lib/signalr/signalr.js"></script> <script src="~/lib/msgpack5/msgpack5.js"></script> <script src="~/lib/signalr/signalr-protocol-msgpack.js"></script>
const connection = new signalR.HubConnectionBuilder() .withUrl("/hqHub") .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol()) .build();
運行日志
REFER:
https://docs.microsoft.com/en-us/aspnet/core/signalr/messagepackhubprotocol?view=aspnetcore-2.1
https://damienbod.com/2018/03/19/using-message-pack-with-asp-net-core-signalr/
https://socket.io/docs/