그룹과 연결 매핑

· 기능

이전 글에서 WebSocket 서버의 새로운 그룹 기능을 소개했어요. 이 글에서는 WebSocket 그룹과 클라이언트 연결을 결합해서 클라이언트 연결에서 사용자 데이터를 식별하고 저장하는 방법을 보여 드릴게요.

sgcWebSockets 라이브러리를 사용하면 직접 객체를 생성하고 TsgcWSConnection 클래스에 연결할 수 있어요. 새 메시지가 수신되거나 클라이언트가 연결 해제될 때 언제든지 사용자 지정 객체에 접근할 수 있어요. 이제 그룹의 사용 편의성과 Custom Objects결합해서 고급 애플리케이션을 쉽게 구축할 수 있어요.

사용자 인증

서버는 인증된 사용자 연결만 허용하도록 설정할 거예요. 먼저 서버 측에서 인증을 활성화하고, OnAuthentication 이벤트를 설정해서 서버가 받은 연결을 인증해요. 사용자는 일반적으로 데이터베이스에 저장되지만, 이 예제에서는 단순화를 위해 하드코딩되어 있어요.

Server.Authentication.Enabled := True;
Server.Authentication.Basic.Enabled := True; 

아래 샘플 코드를 확인하세요. 먼저 사용자 이름/비밀번호가 올바른지 평가하고, 맞으면 사용자 데이터가 저장되는 TsgcUser 클래스의 새 인스턴스를 생성하고, 속성을 채우고 Connection.Data 속성에 할당해요. 이렇게 하면 이 사용자로부터 메시지를 받거나 연결이 해제될 때 사용자 데이터에 접근할 수 있어요.

type
  TsgcUser = class
  private
    FAge: Integer;
    FDepartment: string;
    FPhone: string;
    FUsername: string;
  public
    property Username: string read FUsername write FUsername;
    property Department: string read FDepartment write FDepartment;
    property Phone: string read FPhone write FPhone;
    property Age: Integer read FAge write FAge;
  end;
procedure OnServerAuthentication(Connection: TsgcWSConnection; aUser, 
  aPassword: string; var Authenticated: Boolean);
var
  oUser: TsgcUser;
begin
  if (aUser = 'user-1') and (aPassword = 'password-1') then
  begin
    Authenticated := True;
    oUser := TsgcUser.Create;
    oUser.Username := 'Mark';
    oUser.Phone := '+55431588744134';
    oUser.Department := 'Sales';
    oUser.Age := 22;
    Connection.Data := oUser;
  end
  else
    Authenticated := False;
end; 

사용자가 인증되면 OnConnect 이벤트가 발생해요. 여기서 사용자를 그룹에 추가할 수 있어요. 이 데모에서는 사용자의 Department 속성이 그룹 이름으로 사용돼요. 필요한 만큼 Groups.Add 메서드를 호출해서 연결을 1개 이상의 그룹에 추가할 수 있어요.

procedure OnServerConnect(Connection: TsgcWSConnection);
begin
  Server.Groups.Add(TsgcUser(Connection.Data).Department, Connection);
end; 

클라이언트가 연결 해제되면 연결 클래스가 자동으로 Groups 속성에서 제거되므로 자동으로 처리되기 때문에 수동으로 제거할 필요가 없어요.

이벤트 사용

Groups 속성에는 사용자가 그룹에 추가되거나 제거될 때마다 알리는 2가지 이벤트가 있어요.

OnClientAdded: 새 연결이 그룹에 추가될 때 발생해요.

OnClientRemoved: 기존 연결이 그룹에서 제거될 때 발생해요.

서버가 시작되기 전에 이 이벤트들을 설정할 수 있어요. 다음 예제에서는 새 멤버가 추가되거나 기존 멤버가 연결 해제되었음을 그룹의 모든 멤버에게 메시지로 알려요.

Server.Groups.OnClientAdded := OnClientAddedEvent;
Server.Groups.OnClientRemoved := OnClientRemovedEvent;
procedure OnClientAddedEvent(Sender: TObject; const aGroup:
    TsgcWSServerGroupItem; const aConnection: TsgcWSConnection);
var
  vMessage: string;
begin
  vMessage := TsgcUser(aConnection.Data).Username + ' has logged in.';
  aGroup.BroadCast(vMessage);
end;
procedure TForm16.OnClientRemovedEvent(Sender: TObject; const aGroup:
    TsgcWSServerGroupItem; const aConnection: TsgcWSConnection);
var
  vMessage: string;
begin
  vMessage := TsgcUser(aConnection.Data).Username + ' has disconnected.';
  aGroup.BroadCast(vMessage);
end; 

메시지 보내기

그룹을 사용해 특정 그룹이나 여러 그룹에 메시지를 브로드캐스트할 수 있어요. 아래에서 몇 가지 예제를 확인하세요.

// All members
Server.Groups.Broadcast('*', 'Hello All Members.');
// Only group "admin"
Server.Groups.Broadcast('admin', 'Hello Admin Members.');
// All sales groups (sales/asi, sales/europe, sales/america...)
Server.Groups.Broadcast('sales/*', 'Hello Sales Members.');
// Only group "accounting" (must exists!!!)
Server.Groups.Group['accounting'].Broadcast('Hello Accounting Members.'); 

아래에서 서버 및 클라이언트 애플리케이션의 소스와 Windows용 컴파일된 바이너리를 확인하세요.