如何从C#客户端连接到SignalR集线器

时间:2019-03-29 08:26:17

标签: .net-core signalr client

我有一个Console Application,我正在尝试订阅一个SignalR集线器。 查看互联网上的所有示例,我发现所有人都使用HubConnection来做到这一点。 问题在于,我认为它们都已弃用,因为constructor在他们的情况下使用了url,而在文档中它在使用了IConnectionFactoryILoggerFactory

服务器

public class Startup {

        public void ConfigureServices(IServiceCollection services) {
            services.AddCors(o =>
            o.AddPolicy("CorsPolicty", b => b.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
            services.AddSignalR();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
            app.UseDeveloperExceptionPage();
            app.UseSignalR(r => r.MapHub<MyHub>("/myhub"));
        }
    }


public class MyHub:Hub {
        public async Task SendMessage(string user,string message) {

            await this.Clients.All.SendAsync("ReceiveMessage", user, message);

        }
    }

客户

因此HubConnectionMSDN示例中看起来并不像,我也看过HubConnectionBuilder类,在这种情况下,所有示例都具有WithUrl扩展名,而实际上它有一个IServiceCollection,您可以在其中添加服务。

class ConcreteContext : ConnectionContext {
        public override string ConnectionId { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public override IFeatureCollection Features => throw new NotImplementedException();

        public override IDictionary<object, object> Items { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public override IDuplexPipe Transport { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    }
    class Factory : IConnectionFactory {
        public Task<ConnectionContext> ConnectAsync(TransferFormat transferFormat, CancellationToken cancellationToken = default(CancellationToken)) {
            var context = new ConcreteContext();
            return Task.FromResult(context as ConnectionContext);
        }

        public Task DisposeAsync(ConnectionContext connection) {
            throw new NotImplementedException();
        }
    }
    class Program {
        static void Main(string[] args) {
            //try 1
            var builder = new HubConnectionBuilder().Build(); //no withUrl extensions
            //try 2
            var factory = new Factory();
            var hub = new HubConnection(factory,); //needs IConnectionFactory and IHubProtocol and ILoggerFactory

        }

我不敢相信我必须执行所有这些步骤才能开始连接。如何连接到集线器? 如果我不得不为一件事情写很多东西,我可能会考虑回到原始websockets

1 个答案:

答案 0 :(得分:0)

这个SO问题似乎已解决,但具有从客户端到SignalR Core集线器的连接的链接和参考。

客户端代码看起来比您显示的要简单得多。我会检查出来,并在需要时提供链接。