Message Pack Hub Protocol and Keep Alive in SignalR
SignalR
8 Articles
In this article, let's learn about Message Pack Hub Protocol and Keep Alive in SignalR.
Note: If you have not done so already, I recommend you read the article on Send Notifications to Groups and Connection Id in SignalR.
Table of Contents
Introduction
In our previous article we about what are Groups and Caller ID and how to send notifications to Groups and Caller ID. Today in this article, lets learn about another server and client features which helps in configuring Hub Protocol and Keep Alive available in SignalR.
Message Pack Hub Protocol and Keep Alive
We have learnt that by default a JSON protocol was used as Hub protocol in previous articles. Assuming the WebSocket's transport is used, you can actually see the JSON messages when going to the Network tab of the F12 developer tools of your browser. When you click on the WebSocket connection to the hub and select the Messages tab, you can see the message going through. When you click on it, you can see the actual message.
There are also a number of other messages visible, which are of type:6. These are keepalive messages. They are needed because WebSocket connections tend to close automatically after a certain period of inactivity, and the keepalive messages are preventing that. Since JSON is text, it is not very efficient, especially when dealing with larger messages. When you, for example, work with larger objects that are passed as parameters, JSON protocol might be too slow or too inefficient. In that case, there's the option to switch to MessagePack hub protocol, which is binary.
To enable MessagePack Protocol install the Nuget package Microsoft.AspNetCore.SignalR.Protocols.MessagePack and call AddMessagePackProtocol() to the SignalR setup in server and HubConnectionBuilder in client.
Code Sample - MessagePack Protocol
MessagePack serialization is strictly case-sensitive. That means that the property names of the objects that are sent through the connection should match exactly. So to make this work, we have to use Pascal casing for property names. It's a MessagePack quirk that is not easy to bypass. When we now run the application and look at the messages again, they are now binary. That's an advantage in terms of performance, but it also has a downside. They are not as easy to read as the JSON messages.
Summary
In this article, we learnt about Message Pack Hub Protocol and Keep Alive in SignalR. We also saw how to configure and check them in browser developer tools. In the next article, we will learn about Exceptions and Logging in SignalR.