Search code examples
javascriptc#asp.net-coresignalr

I can receive messages from signalR hub with signalR js libray, but not with WebSocket


I try to implement a way to connect client to a signalR hub. And I can't just take the SignalR library, because I want add this into library builded with rollup (And it's don't build with rollup)

For the tests, I have a Thread send a message to all clients every 10s :

    Thread cyclicThread = ThreadUtils.GetCyclicThread(10000, () =>
    {
        this.NotificationHub.Clients.All.SendAsync("methodeTestBis", 239);
    });
    cyclicThread.Start();

With signalR library, it's work, I can see messages in the network tab of Chrome's debugger.

    // Tests with signalR js library, messages receiving
    const connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

    connection.start();

Network tab where we can see messages with signalR

But when I use WebSocket to handle messages come from the signalR hub, it's not work. The onopen function is triggered, but not the onmessage function, and I didn't see messages for this WebSocket inside the network tab.

// Tests with WebSocket, messages not receiving
    let url = "https://localhost:7143/chatHub";

    const headers = {};
    const [name, value] = getUserAgentHeader();
    headers[name] = value;

    fetch(`${url}/negotiate?negotiateVersion=1`, {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            headers,
        },
        body: JSON.stringify({
            content: "",
            headers: headers,
            timeout: 100000,
            withCredentials: true,
        }),
    }).then((response) => response.json())
        .then((response) => {
            // The fetch return here some information about signalR connection, and the token for idendification
            console.log(response);

            // The web socket for SignalR's connection
            const wsUrl = `${url}?id=${response.connectionToken}`.replace(/^http/, "ws");
            const webSocket = new WebSocket(wsUrl);

            webSocket.onopen = (event) => {
                // It's triggered
                console.log(event);
            }

            webSocket.onmessage = (message) => {
                // It's not triggered
                console.log(message);
            }

            webSocket.onerror = (event) => {
                console.log(event);
                console.log(event.error);
            }

            webSocket.onclose = (event) => {
                console.log(event);
            }
    });

    // The next two functions is from signalR, used for tests and debug what's wrong
    function getUserAgentHeader() {
        let userAgentHeaderName = "X-SignalR-User-Agent";

        return [userAgentHeaderName, constructUserAgent("7.0.5", undefined, "Browser", undefined)];
    }
    function constructUserAgent(version, os, runtime, runtimeVersion) {
        // Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])
        let userAgent = "Microsoft SignalR/";
        const majorAndMinor = version.split(".");
        userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;
        userAgent += ` (${version}; `;
        if (os && os !== "") {
            userAgent += `${os}; `;
        }
        else {
            userAgent += "Unknown OS; ";
        }
        userAgent += `${runtime}`;
        if (runtimeVersion) {
            userAgent += `; ${runtimeVersion}`;
        }
        else {
            userAgent += "; Unknown Runtime Version";
        }
        userAgent += ")";
        return userAgent;
    }

Network tab where we can't see messages with WebSocket

Someone know what I do wrong ?

There is the link to get the signalR library : https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.js

The code I use for make my own WebSocket's code is between lines 2251 and 2342


Solution

  • I find another way to correct my issue.

    Previously, in my react library, I use the next line for import signalR :

        import signalR, { HubConnection } from "@microsoft/signalr";
    

    And now, I use the follow import, and it's work with npm run rollup in my library :

        import * as signalR from "@microsoft/signalr";
    

    And I don't have the error "default is not exported by @microsoft/signalr"