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:
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!