Reputation: 416
I have 2 ASP.NET Core Razor web apps. Each app will be using SignalR to communicate with web app clients and mobile clients. Because of my intended use, I have setup both web apps as Hub and Client, where the Client is using the .NET SignalR Client. Each of the 2 web apps have the following:
static internal HubConnection Connection; // In the Startup class
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Connection = new HubConnectionBuilder()
// Where the URL is for the OTHER web app
.WithUrl("https://localhost:44386/NotificationHub")
.Build();
}
Each project also has a NotificationHub class, derived from Hub, in the Hubs folder.
In the Startup ConfigureServices method in each app I have as the last statement:
services.AddSignalR();
In the Startup Configure method in each app I have the following immediately before the call to UseMvc:
app.UseSignalR(routes =>
{
routes.MapHub<NotificationHub>("/NotificationHub");
});
In each of the NotificationHub classes I have:
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
So, I am unsure how to initially connect from one Client to a Hub and I am also unsure if I am using the URL correctly.
Upvotes: 1
Views: 11087
Reputation: 1405
For using js Client :
1) Install signalr npm : npm install @aspnet/signalr
2) Add the reference in required page
3) Add Connection Object code
const connection = new signalR.HubConnectionBuilder()
.withUrl("/NotificationHub")
.configureLogging(signalR.LogLevel.Information)
.build();
connection.start().catch(err => console.error(err.toString()));
4) Call your require method
connection.invoke("SendMessage", user, message).catch(err => console.error(err.toString()));
For .Net Client
1) install nuget: Install-Package Microsoft.AspNetCore.SignalR.Client
2)
HubConnection connection = new HubConnectionBuilder()
.WithUrl("https://localhost:44386/NotificationHub")
.Build();
await connection.StartAsync();
await connection.InvokeAsync("SendMessage",
"user", "message");
you can start the connection with button click or on sending message
You can find more details in below link :
https://learn.microsoft.com/en-us/aspnet/core/signalr/introduction?view=aspnetcore-2.1
Upvotes: 2