Отключение SignalR Asp.netcore и angular (WebSocket не находится в состоянии OPEN) для signalR.HttpTransportType.WebSockets

Использование .NET Core 2.2 и Angular 8 с пакетом "@aspnet/signalr": "^1.1.4". Я настроил концентратор в .NET Core 2.2, который отлично работает с другим проектом Angular, использующим тот же пакет.

Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SignalrChat.Services;

namespace SignalrChat
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
            {
                builder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed(_ => true)
                .AllowCredentials();
            }));
            services.AddSignalR();
            services.AddSingleton<IChatRoomService, InMemoryChatRoomService>();
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseCors("CorsPolicy");
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/chat");
            });
        }
    }
}

Центр:

using Microsoft.AspNetCore.SignalR;
using SignalrChat.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SignalrChat
{
    public class ChatHub : Hub
    {}
}

Угловой:

import * as signalR from "@aspnet/signalr";
import {
  Component, Inject, OnInit
} from '@angular/core';

import { DeviceDetectorService } from 'ngx-device-detector';
import { DOCUMENT } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    ngOnInit(): void {
        this.hub = new signalR.HubConnectionBuilder()
            .configureLogging(signalR.LogLevel. Trace)
        .withUrl('http://localhost:56328/chat')
        
            .build();

        this.hub.serverTimeoutInMilliseconds = 100000;
        this.hub.keepAliveIntervalInMilliseconds = 100000;
        this.hub
            .start()
            .then(() => {  
                console.log('Connection started!');
                console.log('Getting all rooms');  

            })
            .catch(err => {
                console.log(err);
                console.log(this.hub);
                
            });
    }
}

Вот журнал для hub.start() из проекта Angular, который отлично работает:

[2019-12-31T11:43:30.214Z] Debug: Starting HubConnection.
Utils.js:213 [2019-12-31T11:43:30.215Z] Debug: Starting connection with transfer format 'Text'.
Utils.js:213 [2019-12-31T11:43:30.220Z] Debug: Sending negotiation request: http://localhost:56328/chat/negotiate.
Utils.js:213 [2019-12-31T11:43:31.382Z] Debug: Selecting transport 'WebSockets'.
client:52 [WDS] Live Reloading enabled.
Utils.js:209 [2019-12-31T11:43:32.001Z] Information: WebSocket connected to ws://localhost:56328/chat?id=NafCuVY_brPNmqQlN2EvXw.
Utils.js:213 [2019-12-31T11:43:32.003Z] Debug: Sending handshake request.
Utils.js:209 [2019-12-31T11:43:32.006Z] Information: Using HubProtocol 'json'.
Utils.js:213 [2019-12-31T11:43:32.053Z] Debug: Server handshake complete.

Но для другого углового проекта с точно таким же кодом и пакетом для того же концентратора он не может быть продолжен. Вот журнал:

[2019-12-31T11:41:35.294Z] Debug: Starting HubConnection.
Utils.js:213 [2019-12-31T11:41:35.639Z] Debug: Starting connection with transfer format 'Text'.
Utils.js:213 [2019-12-31T11:41:35.644Z] Debug: Sending negotiation request: http://localhost:56328/chat/negotiate.
core.js:16829 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
Utils.js:213 [2019-12-31T11:41:36.574Z] Debug: Selecting transport 'WebSockets'.
WebSocket connection to 'ws://localhost:4200/sockjs-node/694/1skccdzm/websocket' failed: WebSocket is closed before the connection is established.
[2019-12-31T11:41:38.814Z] Information: WebSocket connected to ws://localhost:56328/chat?id=qO3s36husX9-boU1SwyaBg.
Utils.js:213 [2019-12-31T11:41:38.820Z] Debug: Sending handshake request.
app.component.ts:34 WebSocket is not in the OPEN state

Пробовал менять все пакеты нерабочего ангуляра на такой же как и рабочий ангуляр, проблема так и осталась.

ОБНОВЛЕНИЕ

Я узнал, что изменение режима транспорта http для signalR.HubConnectionBuilder() заставит его работать, как показано ниже:

var options = {
    transport: signalR.HttpTransportType.ServerSentEvents ,
    logging: signalR.LogLevel.Trace, 
};
this.hub = new signalR.HubConnectionBuilder()
    //.withUrl('http://localhost:56328/chat' , options)
    .withUrl('http://localhost:49941/chat', options) 
    .build();

ServerSentEvent выполнен успешно, а режимы websocket и longpolling — нет.


person Salar Kazazi    schedule 31.12.2019    source источник
comment
Если вы просматриваете эти два угловых приложения из одного и того же клиента, одно работает, а другое не работает с транспортом websocket и longpolling?   -  person Fei Han    schedule 01.01.2020
comment
И проверьте, не вызвана ли проблема zone.js.   -  person Fei Han    schedule 01.01.2020
comment
@ Fei Han: Спасибо за ответ, да, у меня есть оба угловых приложения на моем компьютере, одно работает с веб-сокетом, другое работает с serverSentEvent.   -  person Salar Kazazi    schedule 01.01.2020
comment
@ Фей Хан: тот же компьютер*   -  person Salar Kazazi    schedule 01.01.2020


Ответы (1)


Спасибо @Fei Han за упоминание этого полезного решения: оно работало, когда я изменил свой код на это:

 Object.defineProperty(WebSocket, 'OPEN', { value: 1, }); 
        this.hub
            .start()
            .then(() => {                     
                console.log('Connection started!');         

            })
            .catch(err => {
                console.log(err);                     
            });
person Salar Kazazi    schedule 01.01.2020