How to use @microsoft/signalr - 10 common examples

To help you get started, we’ve selected a few @microsoft/signalr examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dotnet / aspnetcore / src / SignalR / clients / ts / FunctionalTests / ts / HubConnectionTests.ts View on Github external
it("sets the user agent header", async (done) => {
            const hubConnection = getConnectionBuilder(t, TESTHUBENDPOINT_URL)
                .withHubProtocol(new JsonHubProtocol())
                .build();

            try {
                await hubConnection.start();

                // Check to see that the Content-Type header is set the expected value
                const [name, value] = getUserAgentHeader();
                const headerValue = await hubConnection.invoke("GetHeader", name);

                if ((t === HttpTransportType.ServerSentEvents || t === HttpTransportType.WebSockets) && !Platform.isNode) {
                    expect(headerValue).toBeNull();
                } else {
                    expect(headerValue).toEqual(value);
                }

                await hubConnection.stop();
                done();
            } catch (e) {
                fail(e);
            }
        });
    });
github dotnet / aspnetcore / src / SignalR / clients / ts / FunctionalTests / ts / ConnectionTests.ts View on Github external
eachHttpClient((httpClient) => {
            if (transportType === HttpTransportType.HttpStreaming && !httpClient.supportsStreaming) {
                return;
            }
            describe(`over ${HttpTransportType[transportType]} with ${(httpClient.constructor as any).name}`, () => {
                it("can send and receive messages", (done) => {
                    const message = "Hello World!";
                    // the url should be resolved relative to the document.location.host
                    // and the leading '/' should be automatically added to the url
                    const connection = new HttpConnection(ECHOENDPOINT_URL, {
                        ...commonOptions,
                        httpClient,
                        transport: transportType,
                    });

                    connection.onreceive = (data: any) => {
                        if ((typeof data === "string" && data === message) ||
                            (data instanceof ArrayBuffer && new TextDecoder("utf-8").decode(data) === message)) {
github dotnet / aspnetcore / src / SignalR / clients / ts / FunctionalTests / ts / HubConnectionTests.ts View on Github external
it("populates the Content-Type header when sending XMLHttpRequest", async (done) => {
        // Skip test on Node as this header isn't set (it was added for React-Native)
        if (typeof window === "undefined") {
            done();
            return;
        }
        const hubConnection = getConnectionBuilder(HttpTransportType.LongPolling, TESTHUB_NOWEBSOCKETS_ENDPOINT_URL)
            .withHubProtocol(new JsonHubProtocol())
            .build();

        try {
            await hubConnection.start();

            // Check what transport was used by asking the server to tell us.
            expect(await hubConnection.invoke("GetActiveTransportName")).toEqual("LongPolling");
            // Check to see that the Content-Type header is set the expected value
            expect(await hubConnection.invoke("GetContentTypeHeader")).toEqual("text/plain;charset=UTF-8");

            await hubConnection.stop();
            done();
        } catch (e) {
            fail(e);
        }
github dotnet / aspnetcore / src / SignalR / clients / ts / FunctionalTests / ts / HubConnectionTests.ts View on Github external
it("sets the user agent header", async (done) => {
            const hubConnection = getConnectionBuilder(t, TESTHUBENDPOINT_URL)
                .withHubProtocol(new JsonHubProtocol())
                .build();

            try {
                await hubConnection.start();

                // Check to see that the Content-Type header is set the expected value
                const [name, value] = getUserAgentHeader();
                const headerValue = await hubConnection.invoke("GetHeader", name);

                if ((t === HttpTransportType.ServerSentEvents || t === HttpTransportType.WebSockets) && !Platform.isNode) {
                    expect(headerValue).toBeNull();
                } else {
                    expect(headerValue).toEqual(value);
                }

                await hubConnection.stop();
github Radarr / Radarr / frontend / src / Components / SignalRConnector.js View on Github external
// see https://github.com/aspnet/AspNetCore/blob/21c9e2cc954c10719878839cd3f766aca5f57b34/src/SignalR/clients/ts/signalr/src/Utils.ts#L147
  if (logLevel >= this.minimumLogLevel) {
    switch (logLevel) {
      case signalR.LogLevel.Critical:
      case signalR.LogLevel.Error:
        console.error(`[signalR] ${signalR.LogLevel[logLevel]}: ${this.cleanse(message)}`);
        break;
      case signalR.LogLevel.Warning:
        console.warn(`[signalR] ${signalR.LogLevel[logLevel]}: ${this.cleanse(message)}`);
        break;
      case signalR.LogLevel.Information:
        console.info(`[signalR] ${signalR.LogLevel[logLevel]}: ${this.cleanse(message)}`);
        break;
      default:
        // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug
        console.log(`[signalR] ${signalR.LogLevel[logLevel]}: ${this.cleanse(message)}`);
        break;
    }
  }
};
github Radarr / Radarr / frontend / src / Components / SignalRConnector.js View on Github external
Logger.prototype.log = function(logLevel, message) {
  // see https://github.com/aspnet/AspNetCore/blob/21c9e2cc954c10719878839cd3f766aca5f57b34/src/SignalR/clients/ts/signalr/src/Utils.ts#L147
  if (logLevel >= this.minimumLogLevel) {
    switch (logLevel) {
      case signalR.LogLevel.Critical:
      case signalR.LogLevel.Error:
        console.error(`[signalR] ${signalR.LogLevel[logLevel]}: ${this.cleanse(message)}`);
        break;
      case signalR.LogLevel.Warning:
        console.warn(`[signalR] ${signalR.LogLevel[logLevel]}: ${this.cleanse(message)}`);
        break;
      case signalR.LogLevel.Information:
        console.info(`[signalR] ${signalR.LogLevel[logLevel]}: ${this.cleanse(message)}`);
        break;
      default:
        // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug
        console.log(`[signalR] ${signalR.LogLevel[logLevel]}: ${this.cleanse(message)}`);
        break;
    }
  }
};
github dotnet / aspnetcore / src / SignalR / clients / ts / FunctionalTests / ts / HubConnectionTests.ts View on Github external
it("over LongPolling it sends DELETE request and waits for poll to terminate", async (done) => {
        // Create an HTTP client to capture the poll
        const defaultClient = new DefaultHttpClient(TestLogger.instance);

        class TestClient extends HttpClient {
            public pollPromise: Promise | null;

            constructor() {
                super();
                this.pollPromise = null;
            }

            public send(request: HttpRequest): Promise {
                if (request.method === "GET") {
                    this.pollPromise = defaultClient.send(request);
                    return this.pollPromise;
                }
                return defaultClient.send(request);
            }
github dotnet / aspnetcore / src / Components / Web.JS / src / Boot.Server.ts View on Github external
async function initializeConnection(options: CircuitStartOptions, logger: Logger, circuit: CircuitDescriptor): Promise {
  const hubProtocol = new MessagePackHubProtocol();
  (hubProtocol as unknown as { name: string }).name = 'blazorpack';

  const connectionBuilder = new signalR.HubConnectionBuilder()
    .withUrl('_blazor')
    .withHubProtocol(hubProtocol);

  options.configureSignalR(connectionBuilder);

  const connection = connectionBuilder.build();

  setEventDispatcher((descriptor, args) => {
    connection.send('DispatchBrowserEvent', JSON.stringify(descriptor), JSON.stringify(args));
  });

  // Configure navigation via SignalR
  window['Blazor']._internal.navigationManager.listenForNavigationEvents((uri: string, intercepted: boolean): Promise => {
    return connection.send('OnLocationChanged', uri, intercepted);
  });
github dotnet / aspnetcore / src / SignalR / clients / ts / FunctionalTests / ts / Common.ts View on Github external
export function eachTransportAndProtocol(action: (transport: HttpTransportType, protocol: IHubProtocol) => void) {
    const protocols: IHubProtocol[] = [new JsonHubProtocol()];
    // Run messagepack tests in Node and Browsers that support binary content (indicated by the presence of responseType property)
    if (typeof XMLHttpRequest === "undefined" || typeof new XMLHttpRequest().responseType === "string") {
        // Because of TypeScript stuff, we can't get "ambient" or "global" declarations to work with the MessagePackHubProtocol module
        // This is only a limitation of the .d.ts file.
        // Everything works fine in the module
        protocols.push(new MessagePackHubProtocol());
    }
    getHttpTransportTypes().forEach((t) => {
        return protocols.forEach((p) => {
            if (t !== HttpTransportType.ServerSentEvents || !(p instanceof MessagePackHubProtocol)) {
                return action(t, p);
            }
        });
    });
}
github damienbod / AspNetCoreAngularSignalR / src / AspNetCoreAngularSignalR / angularApp / app / news / news.service.ts View on Github external
private init() {

        this._hubConnection = new signalR.HubConnectionBuilder()
            .withUrl('https://localhost:44324/looney')
            .configureLogging(signalR.LogLevel.Information)
            .build();

        this._hubConnection.start().catch(err => console.error(err.toString()));

        this._hubConnection.on('Send', (newsItem: NewsItem) => {
            this.store.dispatch(new NewsActions.ReceivedItemAction(newsItem));
        });

        this._hubConnection.on('JoinGroup', (data: string) => {
            console.log('recieved data from the hub');
            console.log(data);
            this.store.dispatch(new NewsActions.ReceivedGroupJoinedAction(data));
        });