unit ClientService;

interface

uses CfgPort, CorrespondClient, Forms, WinSock;

type
  TScClient = class
  private
    FUser: Integer;
    FCfgPort: TScCfgPort;
    FCorrespondClient: TScCorrespondClient;
    function GetComputerIP: string;
    function GetIP: string;
    function GetPort: Integer;
  public
    constructor Create;
    destructor Destroy; override;

    function ConnectServer: Boolean;
    function CheckConnection(AAddr, ABytes: Integer; P: PByte): Boolean;
    procedure CloseConnection;

    property UserType: Integer read FUser write FUser;
    property Port: Integer read GetPort;
    property IP: string read GetIP;
  end;

implementation

uses SysUtils;

{ TScClient }

function TScClient.CheckConnection(AAddr, ABytes: Integer; P: PByte): Boolean;
begin
  Result := FCorrespondClient.ReadDogData(AAddr, ABytes, 9, P);
end;

procedure TScClient.CloseConnection;
begin
  FCorrespondClient.QuestConnect(1);

  FCorrespondClient.CloseConnection;
end;

function TScClient.ConnectServer: Boolean;
begin
  Result := FCorrespondClient.ConnectServer(FCfgPort.Port, FCfgPort.IP);
  if Result then
  begin
    FCorrespondClient.IP := GetComputerIP;
    FCorrespondClient.UserID := FUser;
    Result := FCorrespondClient.QuestConnect(0);
  end;
{  if Result then
    FCorrespondClient.ResumeThrds;}
end;

constructor TScClient.Create;
begin
  
  FCfgPort := TScCfgPort.Create;
  FCorrespondClient := TScCorrespondClient.Create;

  FCfgPort.FileDir := ExtractFilePath(Application.ExeName);
  FCfgPort.ReadPort;
end;

destructor TScClient.Destroy;
begin
  CloseConnection;

  FCfgPort.Free;
  FCorrespondClient.Free;
  inherited;
end;

function TScClient.GetComputerIP: string;
var
  wsData: TWSAData;
  sName: string;
  host: PHostEnt;
begin
  sName := '';
  Result := '';
  WSAStartup(2, wsData);
  host := gethostbyname(Pchar(sName));
  if host <> nil then
    Result := Result + Format('%d.%d.%d.%d', [Byte(host^.h_addr^[0]), Byte(host^.h_addr^[1]),
      Byte(host^.h_addr^[2]), Byte(host^.h_addr^[3])]);
  WSACleanup;
end;

function TScClient.GetIP: string;
begin
  Result := FCfgPort.IP;
end;

function TScClient.GetPort: Integer;
begin
  Result := FCfgPort.Port;
end;


end.
