代码之家  ›  专栏  ›  技术社区  ›  Jamil

带有.NET Core 2.0的信号器

  •  1
  • Jamil  · 技术社区  · 7 年前

    我正试图在Core2.0中使用Signaler如果我将transport设置为longpolling,它会起作用,但我会收到关于超时的警告。我想把它和WebSockets一起使用,但是我得到了

    WebSocket未处于打开状态

    我检查了很多类似的问题,其中大多数是由于系统限制,但我使用的是windows 10和chrome v.67。 我认为问题出在Startup.cs:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors("CorsPolicy");
        app.UseSignalR(routes =>
        {
            routes.MapHub<NotifyHub>("/notify");
        });
    }
    
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
        {
            builder.AllowAnyMethod()
                   .AllowAnyHeader()
                   .WithOrigins("http://localhost:52170/");
        }));
        services.AddSignalR();
    }
    

    正面(字体):

    ngOnInit() {
            let builder = new HubConnectionBuilder();
            this.hubConnection = builder.withUrl("http://localhost:52170/notify", HttpTransportType.WebSockets).build();//'http://localhost:1874/notify').build();
            this.hubConnection.serverTimeoutInMilliseconds = 5000;
            this.hubConnection
                .start()
                .then(() => console.log('Connection started!'))
                .catch(err => console.log(err)); //'Error while establishing connection :('));
            console.log(this.hubConnection);
            this.hubConnection.onclose = e => {
                this.hubConnection.start();
            }
       }
    

    我从浏览器收到这两条消息:

    信息:websocket连接到 ws://localhost:52170/notify?id=SJ4cb49oWZtL6lIt4cqhKg WebSocket不是 处于开放状态

    2 回复  |  直到 7 年前
        1
  •  1
  •   ideepak04    7 年前

    @jamil,我在project上创建的代码是最好的,它正在工作。你能提供更多的细节或比较下面的代码。如果有什么不同,也告诉我。

    --在Startup.cs中

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    
        //DKS: Makes the SignalR services available to the dependency injection system. 
        services.AddCors(options => options.AddPolicy("CorsPolicy",
        builder =>
        {
            builder.AllowAnyMethod().AllowAnyHeader()
                   .WithOrigins("http://localhost:53249")
                   .AllowCredentials();
        }));
    
        services.AddSignalR();
    }
    

    //运行时调用此方法。使用此方法配置http请求管道。

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
    
        app.UseStaticFiles();
    
        app.UseCors("CorsPolicy");
        app.UseSignalR(routes =>
        {
            routes.MapHub<ChatHub>("/chatHub");
        });
    
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    }
    }
    

    ---主页组件

    import { Component, OnInit } from '@angular/core';
    import { HubConnection } from '@aspnet/signalr';
    import * as signalR from '@aspnet/signalr';
    
    @Component({
        selector: 'app-home-component',
        templateUrl: './home.component.html'
    })
    
    export class HomeComponent implements OnInit {
        private _hubConnection: HubConnection | undefined;
        public async: any;
        message = '';
        messages: string[] = [];
    
        constructor() {
        }
    
        public sendMessage(): void {
            const data = `Sent by you: ${this.message}`;
    
            if (this._hubConnection) {
                this._hubConnection.invoke('SendAngular', data);
            }
    
            this.messages.push(data);
        }
        ngOnInit() {
            let builder = new signalR.HubConnectionBuilder();
            this._hubConnection = builder.withUrl("http://localhost:53249/chatHub", signalR.HttpTransportType.WebSockets).build();//'http://localhost:1874/notify').build();
            this._hubConnection.serverTimeoutInMilliseconds = 9999999999999;
            this._hubConnection
                .start()
                .then(() => console.log('Connection started!'))
                .catch(err => console.log(err)); //'Error while establishing connection :('));
            console.log(this._hubConnection);
    
            this._hubConnection.on('Send', (data: any) => {
                const received = `Received by Friend: ${data}`;
                this.messages.push(received);
            });
    
            //this._hubConnection.onclose = e => {
            //    this._hubConnection.start();
            //}
    
        }
    }
    

    using Microsoft.AspNetCore.SignalR;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace SignalRExample.Hubs
    {
        public class ChatHub : Hub
        {
            public Task SendAngular(string data)
            {
                return Clients.All.SendAsync("Send", data);
            }
        }
    }
    
        2
  •  0
  •   ideepak04    7 年前

    注释此行“this.hubConnection.serverTimeoutInMiscellises=5000;”,然后再次检查。

    ServerTimeoutInMiscellises太小。