Home >Backend Development >C++ >How to Build a Real-time Console App with SignalR?

How to Build a Real-time Console App with SignalR?

Linda Hamilton
Linda HamiltonOriginal
2025-01-06 02:56:40716browse

How to Build a Real-time Console App with SignalR?

Console App Example for SignalR Communication

Understanding SignalR

SignalR is a framework for creating real-time web applications. It allows client applications (such as console apps) to connect to server hubs and receive updates when data changes on the server.

Establishing a Connection

To connect a console app to a SignalR hub, you need the following information:

  • Hub URL (e.g., "http://127.0.0.1:8088/")
  • Hub name (e.g., "CustomHub")

Sending a Message

To send a message to a hub, create a proxy for the hub and invoke its "Send" method:

myHub.Invoke("Send", "Hello World");

Listening for Messages

To listen for messages from the hub, register a callback event handler for the "addMessage" method:

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

Server-Side Hub Code

The hub class on the server side should implement the Hub interface and define methods that clients can invoke:

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

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

Custom Hub Name

In the provided example, the hub name is specified as "CustomHub" using the [HubName] attribute. If you omit this attribute or set it to an empty string, the default hub name will be "Chat".

The above is the detailed content of How to Build a Real-time Console App with SignalR?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn