Signalr Console App Example

SignalR Console app example

First of all, you should install SignalR.Host.Self on the server application and SignalR.Client on your client application by nuget :

PM> Install-Package SignalR.Hosting.Self -Version 0.5.2

PM> Install-Package Microsoft.AspNet.SignalR.Client

Then add the following code to your projects ;)

(run the projects as administrator)

Server console app:

using System;
using SignalR.Hubs;

namespace SignalR.Hosting.Self.Samples {
class Program {
static void Main(string[] args) {
string url = "http://127.0.0.1:8088/";
var server = new Server(url);

// Map the default hub url (/signalr)
server.MapHubs();

// Start the server
server.Start();

Console.WriteLine("Server running on {0}", url);

// Keep going until somebody hits 'x'
while (true) {
ConsoleKeyInfo ki = Console.ReadKey(true);
if (ki.Key == ConsoleKey.X) {
break;
}
}
}

[HubName("CustomHub")]
public class MyHub : Hub {
public string Send(string message) {
return message;
}

public void DoSomething(string param) {
Clients.addMessage(param);
}
}
}
}

Client console app:

using System;
using SignalR.Client.Hubs;

namespace SignalRConsoleApp {
internal class Program {
private static void Main(string[] args) {
//Set connection
var connection = new HubConnection("http://127.0.0.1:8088/");
//Make proxy to hub based on hub name on server
var myHub = connection.CreateHubProxy("CustomHub");
//Start connection

connection.Start().ContinueWith(task => {
if (task.IsFaulted) {
Console.WriteLine("There was an error opening the connection:{0}",
task.Exception.GetBaseException());
} else {
Console.WriteLine("Connected");
}

}).Wait();

myHub.Invoke<string>("Send", "HELLO World ").ContinueWith(task => {
if (task.IsFaulted) {
Console.WriteLine("There was an error calling send: {0}",
task.Exception.GetBaseException());
} else {
Console.WriteLine(task.Result);
}
});

myHub.On<string>("addMessage", param => {
Console.WriteLine(param);
});

myHub.Invoke<string>("DoSomething", "I'm doing something!!!").Wait();


Console.Read();
connection.Stop();
}
}
}

How does a console app connect to Azure SignalR Server to get notifications from my Web API


What are the reasons that my console application connects to the Azure SignalR server through my API and not directly? Security or by design?

Based on your description and code, it seems that you have a hub server and integrate with Azure SignalR Service.

In this kind of scenario similar as this official example demonstrated, the service mode of your Azure SignalR Service would be default mode. In this mode, your application works as a typical ASP.NET Core (or ASP.NET) SignalR application, and client would requires hub server to get connected as you did.

For more information about service modes and how to choose the right service mode, please check this doc:

https://docs.microsoft.com/en-us/azure/azure-signalr/concept-service-mode#choose-the-right-service-mode

How to have a Self Hosting signalR server running as as NetCore Console App

As mentioned by Noah, my solution was based on

[https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-5.0&tabs=visual-studio]

But instead was built as a console app referencing Microsoft.AspNetCore.App (2.2.8).

ChatHub

using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;

namespace SignalRServer
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}

Startup

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace SignalRServer
{
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.AddRazorPages();
services.AddSignalR();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
//endpoints.MapRazorPages();
endpoints.MapHub<ChatHub>("/chatHub");
});
}
}
}

Program

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace SignalRServer
{

public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls("http://localhost:2803");
});
}
}

SignalR Communicate between asp.net and Console Application

Assuming you have a Hub class in your console server such as:

public class MyHub : Hub
{
public void SendMessage(string message)
{
Console.WriteLine("Incoming message {0}", message);
}
}

you can access the server from a client web application either through javascript:

<form runat="server">
<div>
<input type="button" id="sendmessage" value="Send from javascript" />
<asp:Button ID="Button1" runat="server" Text="Send from code behind" OnClick="Button1_Click" />
</div>
</form>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="Scripts/jquery-1.6.4.min.js"></script>
<!--Reference the SignalR library. -->
<script src="Scripts/jquery.signalR-2.3.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="http://localhost:8080/signalr/hubs"></script>
<!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
//Set the hubs URL for the connection
$.connection.hub.url = "http://localhost:8080/signalr";

// Declare a proxy to reference the hub.
var _hub = $.connection.myHub;

// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the SendMessage method on the hub.
_hub.server.sendMessage("$");
});
});
});
</script>

or code behind:

protected void Button1_Click(object sender, EventArgs e)
{
//Set the hubs URL for the connection
string url = "http://localhost:8080/signalr";

// Declare a proxy to reference the hub.
var connection = new HubConnection(url);

var _hub = connection.CreateHubProxy("MyHub");

connection.Start().Wait();

_hub.Invoke("SendMessage", "$").Wait();
}

Please, note you need to have the following packages installed in the web application:

Install-Package Microsoft.AspNet.SignalR.JS

Install-Package Microsoft.AspNet.SignalR.Client

As a complete reference, please read https://docs.microsoft.com/en-us/aspnet/signalr/overview/deployment/tutorial-signalr-self-host which my answer was based on.



Related Topics



Leave a reply



Submit