SignalR Server and Client C#

sgcWebSockets supports SignalR and SignalRCore protocols, now we will see an example of how connect to a SignalR Server using a c# sample from CodeProject webpage, you can access to article using the following link:

https://www.codeproject.com/Articles/5162436/Simple-SignalR-Server-and-Client-Applications-Demo#_articleTop

This article shows how create a simple Server and Client using SignalR as protocol, full csharp source is hosted in github

https://github.com/nthdeveloper/SignalRSamples

In the following lines, I will show how connect to this SignalR server using sgcWebSockets library.

Start connection

In order to connect to a SignalR server, we will use TsgcWebSocketClient as websocket client and TsgcWSAPI_SignalR as SignalR API. Create first websocket client and SignalR API and attach SignalR API to WebSocket client.

WSClient := TsgcWebSocketClient.Create(nil);
SignalRAPI := TsgcWSAPI_SignalR.Create(nil);
SignalRAPI.Client := WSClient; 

Then you must set server data connection. In this case, server is listening on url: http://localhost:8080. TsgcWebSocketClient has a property called URL where we can set URL of websocket server, as we will use websocket protocol our url will be: ws://localhost:8080 

WSClient.URL := 'ws://localhost:8080'; 

 Finally, SignalR requires a Hub name, in this demo, hub name is simplehub.

  SignalRAPI.SignalR.Hubs.Clear;
  SignalRAPI.SignalR.Hubs.Add('simplehub'); 

Then, we can call WSClient.Active := True to start a new connection. If server is active, we will receive a message from server informing a successful connection.

Send Message 

 Once connected, we can send a message to server, we will use WriteData method from TsgcWSAPI_SignalR component. SignalR uses a propietary protocol, basically is a JSON message with some arguments. In this example, method is called Send and argument is text message. Messages are received OnSignalRMessage event.

SignalRAPI.WriteData(Format('{"H":"simplehub","M":"Send","A":["%s"],"I":1}', [txtMessage.Text]));

procedure OnSignalRSignalRMessage(Sender: TObject; MessageId, aData: string);
begin
  DoLog('[' + MessageId + '] ' + aData);
end; 

Join / Leave messages 

 Server sample has 2 methods to join and leave users from a group. Message format is very similar to Send message, let's see some examples:

// join myGroup
SignalRAPI.WriteData(Format('{"H":"simplehub","M":"JoinGroup","A":["%s"],"I":2}', ['myGroup']));

// leave myGroup
SignalRAPI.WriteData(Format('{"H":"simplehub","M":"LeaveGroup","A":["%s"],"I":3}', ['myGroup'])); 

Download

You can download compiled project for C# and Delphi using the following link:

 

File Name: SignalRSample
File Size: 2.7 mb
Download File
File Name: SignalR_source
File Size: 477 kb
Download File
×
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

Discord API Component
FMXLinux Components

Related Posts