⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 querysendthread.pas.~2~

📁 基于delphi的门禁考勤系统
💻 ~2~
字号:
unit QuerySendThread;

interface

uses
  Classes, Messages, Forms, SysUtils, Windows, WinSock, ExtCtrls, StdCtrls,
  DB, ADODB, ComObj, DateUtils, ActiveX;

type
  TQuerySendThread = class(TThread)
  private
    { Private declarations }
    CliSocket,Upload,Sendtime,executecount,conninterval: integer;
    CliAddrIn: TSockAddrIn;
    procedure InitSocket;
    procedure SockConnect;
    procedure SendData(SendRec: string);
    procedure ModifyRec(Recrecord: string; changeState: string );
    procedure GetSendData;
    procedure show;
    function ReceiveText: string;
    function ReceiveBuf(var Buf; Count: Integer): Integer;
    function getCurrentDayFileName: string;
  protected
    procedure Execute; override;
    destructor Destroy;
  end;

implementation

Uses Unit4;

var
  showstr,SendCount: string;
  connectstate: boolean;

{ TQueryandSend }

destructor TQuerySendThread.Destroy;
begin
  CoUnInitialize;
  inherited Destroy;
end;

procedure TQuerySendThread.Execute;
begin
  { Place thread code here }
  inherited;
  FreeOnTerminate := True;
  CoInitialize(nil);
  connectstate := False;
  Upload := StrToInt(IniFile.ReadString('Upload.Interval', 'value', '10'));
  Sendtime := StrToInt(IniFile.ReadString('Send.Interval', 'value', '10000'));
  conninterval := StrToInt(IniFile.ReadString('conn.interval','value','60'));
  SendCount:= IniFile.ReadString('SendCount','value','20');
  InitSocket;
  SockConnect;
  sleep(10000);
  while True do
  begin
    if connectstate then GetSendData;
    Inc(executecount);
    if executecount = conninterval then begin
      CloseSocket(CliSocket);
      InitSocket;
      SockConnect;
      executecount := 0;
    end;
    sleep(Sendtime);
  end;
  if Terminated then Exit;
end;

procedure TQuerySendThread.InitSocket;
var
  WSAData: TWSAData;
begin
  if(WSAStartup(MAKEWORD(2,0),WSAData)<>0) then begin
    showstr :='Winsock Init Failed!';
    synchronize(show);
    exit;
  end;
  CliSocket := socket(AF_INET, SOCK_STREAM,IPPROTO_IP);
  if CliSocket = INVALID_SOCKET then begin
    showstr := '无法创建Socket句柄!';  
    synchronize(show);
    CloseSocket(CliSocket);
    exit;
  end;
end;

procedure TQuerySendThread.SockConnect;
var
  err: integer;
begin
  CliAddrIn.sin_addr.s_addr:= inet_addr(PChar(IniFile.ReadString('IP', 'value', '220.231.232.44')));
  CliAddrIn.sin_family := AF_INET;
  CliAddrIn.sin_port := htons(StrToInt(IniFile.ReadString('PORT', 'value', '10000')));
  repeat
    err := connect(CliSocket,CliAddrIn, SizeOf(CliAddrIn));
    if  err = -1 then begin
      connectstate := false;
      Form4.StatusBar1.Panels[0].Text := '未连接到远程!';
      sleep(5000);
    end else begin
      connectstate := True;
      Form4.StatusBar1.Panels[0].Text := '连接到远程:' + IniFile.ReadString('IP', 'value', '220.231.232.44') + ':' + IniFile.ReadString('PORT', 'value', '10000');
    end;
  until err = 0;
end;

procedure TQuerySendThread.show;
begin
  Form4.Memo2.Lines.Add(showstr);
end;

procedure TQuerySendThread.ModifyRec(Recrecord: string; changeState: string);
var
  fn: string;
  ADOQuery1: TADOQuery;
begin
  fn := getCurrentDayFileName();
  ADOQuery1 := TADOQuery.Create(Nil);
  try
  begin
    with ADOQuery1 do
    begin
      ConnectionString := 'DRIVER={Microsoft Access Driver (*.mdb)};  DBQ=' + fn + '; Mode=ReadWrite' + '; Persist Security Info=False';
      SQL.text := format('update infolog set activestate= ' + changeState + ', uploaddate=CDATE(now) where (cardno=''%s'')  and (opdate=CDATE(''%s''))', [Copy(Recrecord, 1, 10), Copy(Recrecord, 11, 19)]);
      ExecSQL;
    end;
  end;
  finally
    FreeAndNil(ADOQuery1);
  end;
end;

function TQuerySendThread.ReceiveBuf(var Buf; Count: Integer): Integer;
var
  FdSet: TFDSet;
  TimeVal: TTimeVal;
begin
  if (Count = -1) then
    ioctlsocket(CliSocket, FIONREAD, Longint(Result))
  else begin
    TimeVal.tv_sec := 0;
    TimeVal.tv_usec := 500;
    FD_ZERO(FDSet);
    FD_SET(CliSocket,FDSet);
    if (select(0,@fdSet,nil,nil,@TimeVal) > 0) then begin
      Result := recv(CliSocket,Buf,Count, 0);
      if Result = SOCKET_ERROR then begin
        if WSAGetLastError <> WSAEWOULDBLOCK then begin
          showstr := 'error receive data' + WSAGetLastError;
          synchronize(show);
          CloseSocket(CliSocket);
          InitSocket;
          SockConnect;
        end;
      end;
    end;
  end;
end;

function TQuerySendThread.ReceiveText: string;
begin
  SetLength(Result, ReceiveBuf(Pointer(nil)^, -1));
  ReceiveBuf(Pointer(Result)^, Length(Result));
end;

procedure TQuerySendThread.GetSendData;
var
  i: Integer;
  fn,SendStr,tmpstr,info: string;
  datetime: TDateTime;
  ADOQuery1: TADOQuery;
begin
  fn := getCurrentDayFileName();
  if not FileExists(fn) then exit;
  ADOQuery1 := TADOQuery.Create(Nil);
  try
    with ADOQuery1 do
    begin
      ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + fn + '; Mode=ReadWrite' + '; Persist Security Info=False';
      SQL.Text := 'select top ' + SendCount + ' * from infolog where activestate = ' + '''1''' + ' and recadddate  < ' + '#' + FormatDateTime('yyyy-mm-dd hh::mm::ss', now - 10/(60*24*24)) + '#' + ' or (activestate = ' + '''3''' + ' and uploaddate  < ' + '#' + FormatDateTime('yyyy-mm-dd hh::mm::ss', now - Upload/(60*24)) + '#)';

//      SQL.Text := 'select top ' + SendCount + ' * from infolog where activestate = ' + '''1''' + ' or (activestate = ' + '''3''' + ' and uploaddate  < ' + '#' + FormatDateTime('yyyy-mm-dd hh::mm::ss', now - Upload/(60*24)) + '#)';
      Open;
    end;
    if not ADOQuery1.IsEmpty then begin
      with ADOQuery1 do begin
        First;
        while not Eof do begin
          SendStr := (ADOQuery1.FieldByName('cardno').AsString +
                      FormatDateTime('YYYY-MM-DD hh:mm:ss', StrToDateTime(ADOQuery1.FieldByName('opdate').AsString)) +
                      ADOQuery1.FieldByName('readerid').AsString);
          SendData(SendStr);
          ModifyRec(SendStr,'3');
//          if Form4.Visible then begin
            showstr := '客户端上传记录:' + SendStr;
            synchronize(show);
//          end;
          Next;
        end;
      end;
    end;
    info := ReceiveText;                       //receive data
    for i := 1 to (length(Info) div 41) do begin
      tmpStr := Copy(Info,(i-1)*41 + 1, 41);
      if TryStrToDateTime(Copy(tmpStr,11,19), datetime) then begin
//        if Form4.Visible then begin
          showstr := '收到回执: ' + tmpstr;
          synchronize(show);
//        end;
        ModifyRec(tmpStr, '2');
      end;
    end;
  finally
    FreeAndNil(ADOQuery1);
  end;
end;

procedure TQuerySendThread.SendData(SendRec: string);
begin
  SendRec := '  ' + IntToStr(length(SendRec) + 4) + SendRec;
  if Send(CliSocket,Pointer(SendRec)^,Length(SendRec),0) = SOCKET_ERROR then exit;
end;

function TQuerySendThread.getCurrentDayFileName: string;
var
  FileNamePath: string;
begin
  FileNamePath := ExtractFilePath(Paramstr(0));
  CreateDirectory(PChar((FileNamePath) + 'Log'), nil);
  result := FileNamePath + 'Log\' + FormatDateTime('yyyy', Now) + IntToStr(WeekOf(Now)) + '.out';
end;

end.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -