作者:DYongLi | 来源:互联网 | 2024-12-11 13:17
本文档提供了一个使用TSimpleMsgPack组件在Delphi环境中进行消息打包与解包的示例。
模块定义如下:
unit uMain;
interface
uses
SimpleMsgPack, Vcl.Forms, System.SysUtils, System.Variants, Vcl.Controls, Vcl.Dialogs, IdTCPServer, IdThreadMgrPool, uDM;
const
cmdQuerySQL = 1;
type
TForm1 = class(TForm)
IdTCPServer1: TIdTCPServer;
IdThreadMgrPool1: TIdThreadMgrPool;
procedure IdTCPServer1Execute(AThread: TIdPeerThread);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
var
msgPack: TSimpleMsgPack;
inputStream, outputStream: TStream;
dataModule: TfrmDM;
begin
inputStream := TMemoryStream.Create;
outputStream := TMemoryStream.Create;
dataModule := TfrmDM.Create(nil);
try
try
AThread.Connection.ReadStream(inputStream, -1, False);
inputStream.Position := 0;
msgPack := TSimpleMsgPack.Create;
try
msgPack.DecodeFromStream(inputStream);
case msgPack.ForcePathObject('cmd').AsInteger of
cmdQuerySQL:
begin
msgPack.ForcePathObject('result').AsVariant := dataModule.QuerySQL(msgPack.ForcePathObject('sql').AsString);
end;
else
msgPack.ForcePathObject('error').AsString := '未知命令';
end;
finally
msgPack.EncodeToStream(outputStream);
end;
outputStream.Position := 0;
AThread.Connection.WriteStream(outputStream, True, False);
except
on E: Exception do
begin
ShowMessage('处理请求时发生错误: ' + E.Message);
end;
end;
finally
FreeAndNil(inputStream);
FreeAndNil(outputStream);
FreeAndNil(dataModule);
end;
end;
end.