Table of Contents
需要掌握的内容 20190326
1.利用IHubContext<>来实现API
2.配置Cors
1.Transports
SignalR supports the following techniques for handling real-time communication:
WebSockets
Server-Sent Events
Long Polling
SignalR automatically chooses the best transport method that is within the capabilities of the server and client.
SignalR的数据传输模式 有三种传输模式:
LongLooping(长轮询)、
WebSocket(HTML5的WEB套接字)、
Forever Frame(隐藏框架的长请求连接),
可以在WEB客户端显式指定一种或几种;也可以采取默认(推荐);若采取默认,SignalR会根据浏览器的环境自动选择合适的传输方式。
2.server
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("SignalrCore",
policy => policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://www.iaspnetcore.com")
.AllowCredentials());
});
services.AddSignalR();
services.AddSingleton<IServiceProvider, ServiceProvider>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); }
//跨域支持
app.UseCors("SignalrCore");
app.UseStaticFiles();
//注册hub
app.UseSignalR(routes =>
{
routes.MapHub("/chat");
routes.MapHub("/signalrHubs");
});
app.UseWebSockets();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
3. enable MessagePackProtocol
3.1
step 1: Add Microsoft.AspNetCore.SignalR.Protocols.MessagePack
3.2
step2: change services.AddSignalR();
to services.AddSignalR() .AddMessagePackProtocol();
4.Configure WebSocket proxying in Nginx
To turn a connection between a client and server from HTTP/1.1 into WebSocket, the protocol switchmechanism available in HTTP/1.1 is used.
see:How to configure nginx as reverse proxy for websocket
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade"; #error
.