TList实现的任务队列
var
g_tasks: TList;type
PTRecvPack = ^TRecvPack;TRecvPack = record // 接收到的原数据
socket: TCustomWinSocket; data: AnsiString; end;procedure TForm1.ssocketClientRead(Sender: TObject; Socket: TCustomWinSocket);
var Pack: AnsiString; pRecvPack: PTRecvPack;begin try // 接收数据 FData := FData + Socket.ReceiveText; // 处理粘包 while Pos(TAILCHAR, FData) > 0 do begin // 取一个完整的数据包 FData := ArrestStringEx(FData, HEADCHAR, TAILCHAR, Pack); // 加入任务队列 New(pRecvPack); pRecvPack^.socket := Socket; pRecvPack^.data := Pack; g_tasks.Add(pRecvPack); end; except on e: Exception do WriteLog('TForm1.ssocketClientRead ' + e.Message); end;end;procedure TWorkerThread.Execute;
var pRecvPack: PTRecvPack; pDecodePack: PTDecodePack; len: Integer;begin inherited; try while not Self.Terminated do begin Sleep(1); // 取一个数据包 从队列 g_tasks.Lock; try if g_tasks.Count = 0 then Continue; pRecvPack := g_tasks.Items[0]; g_tasks.Delete(0); finally g_tasks.UnLock; end; // 开始解码 New(pDecodePack); pDecodePack^.socket := pRecvPack^.socket; // 解码包头 pDecodePack^.msgHead := DecodeMessage(LeftStr(pRecvPack^.data, DEFBLOCKSIZE)); // 解码包体 如有 len := Length(pRecvPack^.data); if len > DEFBLOCKSIZE then pDecodePack^.msgBody := DecodeString(RightStr(pRecvPack^.data, len - DEFBLOCKSIZE)); // 释放指针 if pRecvPack <> nil then Dispose(pRecvPack); // 处理消息 开始 case pDecodePack^.msgHead.MsgID of CM_LOGIN: Self.login(pDecodePack); CM_PASSWORD: Self.password(pDecodePack); CM_CTOC: Self.cToc(pDecodePack); // CM_QRY:end;
// 释放指针 if pDecodePack <> nil then Dispose(pDecodePack); end; except on e: Exception do WriteLog('TWorkerThread.Execute ' + e.Message); end;end;