客户端无法使用 SignalR 连接到服务器端。
状态一直是未连接
连接前信息:
Information: Normalizing '/hub/test' to 'https://localhost:4200/hub/test'.
稍等片刻,错误日志显示WebSocket超时。然后它使用 SSE 连接到服务器。
错误如下:
WebSocket connection to wss://localhost:4200/hub/test?id=MzFJgytPbR9VgqZNeeWYXg`
failed: WebSocket opening handshake timed out
Failed to start the transport 'WebSockets': Error: WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.
服务器端的 Program.cs 如下:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSignalR().AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseRouting();
app.UseWebSockets(new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromSeconds(120),
});
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<TestHub>("/hub/test");
});
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
客户端:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
public hubconnection!: HubConnection;
public customData: CustomData = {} as CustomData;
constructor() {
this.initWebSocket();
}
initWebSocket() {
this.hubconnection = new HubConnectionBuilder()
.withUrl('/hub/test')
.build();
this.hubconnection.on('Update', (data: CustomData ) => {
console.log(data);
this.customData = data;
});
this.hubconnection.on('Notify', (user: string) => {
console.log(user);
alert(user + ' updated the data');
});
this.hubconnection.start().then(
() => this.hubconnection.invoke('Register', 'User' + Math.floor(Math.random() * 10001)).catch(
function (err) {
return console.error(err.toString());
}));
}
}
根据您的描述,您的中心网址似乎是错误的,4200 端口通常是一个角度应用程序网址,而不是服务器应用程序的网址。
您需要检查您的 asp.net 核心的 url,然后在中心 url 中使用它。
像这样:
initWebSocket() {
this.hubconnection = new HubConnectionBuilder()
.withUrl('https://localhost:64261/hub/test')
.build();