unit U_Link;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  IniFiles,Dialogs, ScktComp, ExtCtrls;

type
  TCommBlock = record
                 workFlag:integer;    //0:开始接受字符串，
                 linkString:string[255];
               //  buf:array [0..Buffersize] of char;
               end;
  TfrmLink = class(TForm)
    CSocket: TClientSocket;
    AADs: TPanel;
    procedure CSocketRead(Sender: TObject; Socket: TCustomWinSocket);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure CSocketConnect(Sender: TObject; Socket: TCustomWinSocket);
    procedure FormDestroy(Sender: TObject);
    procedure CSocketError(Sender: TObject; Socket: TCustomWinSocket;
      ErrorEvent: TErrorEvent; var ErrorCode: Integer);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    fADOConnString:string;
    LinkFlag:string;
    function  LinkTxServer():Boolean;

    { Public declarations }
  end;

var
  frmLink: TfrmLink;

implementation
//uses U_Main;
{$R *.dfm}
function  TfrmLink.LinkTxServer():Boolean;
var
  CommBlock : TCommBlock;
begin
  result:=false;
  try
    CommBlock.workFlag:=strtointdef(LinkFlag,-1);
    CommBlock.linkString:='';
    CSocket.Socket.SendBuf(CommBlock,SizeOf(CommBlock));
    Result:=true;
  except
    Application.MessageBox('连接通讯服务器失败！','错误信息',MB_ICONERROR);
  end;
end;

procedure TfrmLink.CSocketRead(Sender: TObject; Socket: TCustomWinSocket);
var
  CommBlock1: TCommBlock;
begin
  try
    CSocket.Socket.ReceiveBuf(CommBlock1,SizeOf(CommBlock1));
    fADOConnString:=trim(CommBlock1.linkString);
    ModalResult:=1;
  except
    ModalResult:=-1;
  end;
end;

procedure TfrmLink.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action:=cahide;
end;

procedure TfrmLink.CSocketConnect(Sender: TObject;
  Socket: TCustomWinSocket);
begin
  if not  LinkTxServer() then   ModalResult:=-1;
end;

procedure TfrmLink.FormDestroy(Sender: TObject);
begin
  frmLink:=nil;
end;

procedure TfrmLink.CSocketError(Sender: TObject; Socket: TCustomWinSocket;
  ErrorEvent: TErrorEvent; var ErrorCode: Integer);
begin
  Application.MessageBox('连接通讯服务器失败！','错误信息',MB_ICONERROR);
  application.Terminate;
end;

procedure TfrmLink.FormCreate(Sender: TObject);
var
  IniFile: TIniFile;
  LinkServer:string;
begin
  try
    IniFile := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'SYSTEMSET.INI');
    LinkServer := IniFile.ReadString('SERVER', '服务器地址','127.0.0.1');
    LinkFlag:= IniFile.ReadString('SERVER', '服务器地址类型','0');
  finally
    IniFile.Free;
  end;

  try
    CSocket.Host:=trim(LinkServer);
    CSocket.Port:=47936;
    CSocket.Open;
  except
    ModalResult:=-1;
  end;

end;

end.
