SignalR Console App Example
In this article, we'll explore an example of a console application using SignalR to communicate with a .NET hub.
SignalR Setup
Before proceeding, ensure the following SignalR packages are installed in both the server and client applications via NuGet:
Server Implementation
Create a console app server with the following code:
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); server.MapHubs(); server.Start(); Console.WriteLine("Server running on {0}", url); 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 Implementation
In a separate console app client:
using System; using SignalR.Client.Hubs; namespace SignalRConsoleApp { internal class Program { private static void Main(string[] args) { var connection = new HubConnection("http://127.0.0.1:8088/"); var myHub = connection.CreateHubProxy("CustomHub"); connection.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("Error opening connection: {0}", task.Exception.GetBaseException()); } else { Console.WriteLine("Connected"); } }).Wait(); myHub.Invoke<string>("Send", "HELLO World ").ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("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(); } } }
Issues and Solutions
Assigning a Hub Name
If you encounter issues with a specific hub name ("test") in your server-side code (e.g., [HubName("test")]), ensure that it doesn't conflict with the HubName attribute in the client-side code. The hub name used in both the server and client must match for proper communication.
The above is the detailed content of How to Build a Simple SignalR Console Application with a Server and Client?. For more information, please follow other related articles on the PHP Chinese website!