Course contentsShow
← C#
Lesson 1488 of 1,90813. Real-time Communication with SignalRFree lesson

Custom Protocol Implementation

Build custom IHubProtocol implementations for niche binary formats or legacy system interop.

Customizing the SignalR Wire Format

In this lesson, you will learn how to implement the IHubProtocol interface to enable SignalR to communicate using non-standard binary formats, allowing seamless integration with legacy systems or specialized high-performance hardware.

By default, SignalR uses JSON or MessagePack to serialize messages sent between the client and the server. However, in enterprise environments dealing with legacy protocols (like fixed-length binary headers or proprietary encoding), you may need to bypass these defaults. Implementing a custom protocol allows you to define exactly how a HubMessage is transformed into bytes and transmitted over the wire.

Implementing IHubProtocol

To create a custom protocol, you must implement IHubProtocol, which requires you to define how to encode and decode messages. You effectively act as the "translator" between the .NET objects the Hub handles and the raw binary stream.

public class MyLegacyProtocol : IHubProtocol
{
    public string Name => "my-legacy-protocol";
    public int Version => 1;
    public TransferFormat TransferFormat => TransferFormat.Binary;

    public bool TryParseMessage(ref ReadOnlySequence<byte> input, IInvocationBinder binder, out HubMessage message)
    {
        // Logic to interpret your specific binary format
        // and convert it into a concrete HubMessage type
    }

    public void WriteMessage(HubMessage message, IBufferWriter<byte> output)
    {
        // Logic to convert the HubMessage into your 
        // proprietary binary byte array
    }

    // Additional methods for Handshake and Binding are also required...
}

The core of this implementation relies on the IBufferWriter<byte> to write your binary data directly to the transport layer. Once implemented, you register your protocol in Program.cs using .AddHubOptions<MyHub>(o => o.AddHubProtocol(new MyLegacyProtocol())).

When to Use This

This approach is strictly for scenarios where you lack control over the client-side serialization logic or are dealing with hardware constraints. Because custom protocols are more complex to maintain and lack the tooling support of JSON, avoid this unless interoperability with a legacy system requires a specific wire format that standard libraries cannot provide.

Key Takeaway: Implementing IHubProtocol gives you complete control over message serialization, enabling SignalR to bridge the gap between modern real-time architecture and rigid, legacy binary communication standards.