The client side can't connect to server side with SignalR.
The status is always not connected.
The information before connecting:
Information: Normalizing '/hub/test' to 'https://localhost:4200/hub/test'.
After waiting for a while, the error log shows that the time out of WebSocket. And then it uses SSE to connect to server.
The error as bellow:
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.
The Program.cs on sever side as bellow:
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();
The client side:
@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());
}));
}
}
According to your description ,it seems your hub url is wrong, the 4200 port is normally an angular application url not the server app's url.
You need to check your asp.net core's url and then use it inside the hub url.
Like this:
initWebSocket() {
this.hubconnection = new HubConnectionBuilder()
.withUrl('https://localhost:64261/hub/test')
.build();