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

이 글은 SignalR 프로토콜을 사용해 간단한 서버와 클라이언트를 만드는 방법을 보여줘요. 전체 C# 소스는 GitHub에 호스팅되어 있어요.

https://github.com/nthdeveloper/SignalRSamples

다음 내용에서 sgcWebSockets 라이브러리를 사용해 이 SignalR 서버에 연결하는 방법을 안내할게요.

연결 시작

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'); 

그런 다음 WSClient.Active := True를 호출해 새로운 연결을 시작할 수 있어요. 서버가 활성화되어 있으면 연결 성공을 알리는 서버 메시지를 받아요.

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'])); 

다운로드

다음 링크에서 C# 및 Delphi용 컴파일된 프로젝트를 다운로드할 수 있어요: