我从SignalR客户端应用程序连接到SignalRHub时遇到问题,下面给出的是错误日志 -
info: Microsoft.AspNetCore.Sockets.Client.WebSocketsTransport[0]
02/01/2018 15:20:13: Connection Id f763a939-3fb9-4812-ae6e-dfe3198ab37b: Starting transport. Transfer mode: Text.
fail: Microsoft.AspNetCore.Sockets.Client.HttpConnection[9]02/01/2018 15:20:13: Connection Id f763a939-3fb9-4812-ae6e-dfe3198ab37b: Failed to start connection. Error starting transport 'WebSocketsTransport'.
System.Net.WebSockets.WebSocketException (0x80004005): Unable to connect to the remote server ---> System.Net.WebException: The remote server returned an error: (404) Not Found.
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Net.WebSockets.ClientWebSocket.<ConnectAsyncCore>d__21.MoveNext()
at System.Net.WebSockets.ClientWebSocket.<ConnectAsyncCore>d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Sockets.Client.WebSocketsTransport.<Connect>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Sockets.Client.WebSocketsTransport.<StartAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Sockets.Client.HttpConnection.<StartTransport>d__46.MoveNext()
SignalR集线器在无状态服务结构服务中运行,并部署在天蓝色服务结构集群上。
在服务器端,我正在使用nuget库
Microsoft.AspNetCore.SignalR
下面给出的是AspNetCore 2.0 无状态服务端代码供参考 -
Startup.cs: -
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace SampleChat
{
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.AddMvc();
services.AddSignalR();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.UseMvc();
app.UseFileServer();
app.UseCors("CorsPolicy");
app.UseWebSockets();
app.UseSignalR(routes => { routes.MapHub<ChatHub>("SignalRHub"); });
}
}
}
ChatHub.cs: -
using Microsoft.AspNetCore.SignalR;
namespace SampleChat
{
public class ChatHub : Hub
{
public void Send(string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.InvokeAsync("Send", message);
}
}
}
SampleChat.cs
using System.Collections.Generic;
using System.Fabric;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.ServiceFabric.Services.Communication.AspNetCore;
using Microsoft.ServiceFabric.Services.Communication.Runtime;
using Microsoft.ServiceFabric.Services.Runtime;
namespace SampleChat
{
/// <summary>
/// The FabricRuntime creates an instance of this class for each service type instance.
/// </summary>
internal sealed class SampleChat : StatelessService
{
public SampleChat(StatelessServiceContext context)
: base(context)
{
}
/// <summary>
/// Optional override to create listeners (like tcp, http) for this service instance.
/// </summary>
/// <returns>The collection of listeners.</returns>
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new[]
{
new ServiceInstanceListener(serviceContext =>
new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
return new WebHostBuilder()
.UseKestrel()
.ConfigureServices(
services => services
.AddSingleton(serviceContext))
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseUrls(url)
.Build();
}))
};
}
}
}
在客户端我正在使用nuget库Microsoft.AspNetCore.SignalR.Client
下面给出的是SignalR客户端代码 -
的Program.cs: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleChatCoreApplication
{
class Program
{
static void Main(string[] args)
{
try
{
SignalRConnector.ConnectoToSignalR().GetAwaiter().GetResult();
}
catch (Exception ex)
{
Console.WriteLine(ex);
};
Console.ReadKey();
}
}
}
SignalRConnector.cs: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
namespace SampleChatCoreApplication
{
static class SignalRConnector
{
public static async Task<bool> ConnectoToSignalR()
{
var connection = new HubConnectionBuilder()
.WithUrl("http://localhost:8634/SignalRHub")
.WithConsoleLogger()
.WithTransport(Microsoft.AspNetCore.Sockets.TransportType.WebSockets)
.Build();
connection.On<string>("Send", data =>
{
Console.WriteLine($"Received data: {data}");
});
await connection.StartAsync();
await connection.InvokeAsync("Send", "Send data to Hub");
Console.ReadKey();
return true;
}
}
}
当我在本地系统中运行无状态服务时,我能够成功连接SignalR Hub。
当服务在Azure服务架构集群上运行时,我不确定为什么在将SignalR客户端与SignalR集线器连接时遇到问题。
有关我检查过网络的其他信息 负载平衡器规则,并没有连接问题 网络方面。 (我已通过在此添加控制器来验证它 服务,我能够从控制器检索结果。)
答案 0 :(得分:0)
我做了一些R&amp; D,发现问题可能与负载均衡器亲和力有关。为了验证Load Balancer Affinity问题,我已经使用HTTP协议部署了应用程序,并且我能够在多次重试连接尝试中与它连接。这给了我一个暗示,Load Balancer Affinity可以在这里引起问题。 此外,我已检查应用程序端口的负载均衡器规则,并发现负载分配设置为无。根据我的理解,它应该是&#34; SourceIPProtocol&#34;。 目前,该服务部署在5节点服务结构集群中,当我将服务缩减到1个节点时,我能够通过HTTP和HTTPS协议使用.net框架应用程序在第一次尝试时与服务连接。
使用自签名证书部署服务。
此处唯一的问题是我无法通过HTTPS协议从.net标准应用程序连接该服务并获取错误 -
The certificate authority is invalid or incorrect
为了从.net框架应用程序连接,我在信号器连接代码之前写下面的给定行 -
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
上面给出的代码在.net标准应用程序中不起作用。
通过进一步的R&amp; D,我发现在.NET Core中,ServicePointManager
被HttpClientHandler
实例本身的配置所取代。您需要在IHubConnectionBuilder实例上调用.WithMessageHandler
并提供设置为ServerCertificateCustomValidationCallback
的HttpClientHandler实例。
当我使用下面给出的代码时,我无法通过HTTPS协议连接SignalR集线器 -
var handler = new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => { return true; }
};
Connection = new HubConnectionBuilder()
.WithUrl(url)
.WithTransport(Microsoft.AspNetCore.Sockets.TransportType.WebSockets)
.WithMessageHandler(handler)
.Build();
当我将传输更改为TransportType.ServerSentEvents或TransportType.LongPolling时,我能够毫无问题地连接SignalR集线器。