MSGPACK跨平台的数据序列规范,为多种语言所支持。用它序列还是还原数据都异常方便。
而且它支持序列的数据格式非常之多,因为它支持的数据格式多,所以MSGPACK的第二功用:缓存。
DELPHI的MSGPACK类库,优秀的QDAC开源项目提供了很好的实现方法。
闲话少说,直接上码。
变量定义:
var
FMsgPack:TSimpleMsgPack;
FSendStream:TMemoryStream;
FRecvStream:TMemoryStream;
创建对象
FMsgPack := TSimpleMsgPack.Create;
FRecvStream := TMemoryStream.Create;
FSendStream := TMemoryStream.Create;
序列数据并发送
FSendStream.Clear;
FRecvStream.Clear;
FMsgPack.Clear;
FMsgPack.ForcePathObject('cmd.index').AsInteger := 1;
FMsgPack.ForcePathObject('cmd.data').AsVariant := vData;
FMsgPack.EncodeToStream(FSendStream);
TStreamCoderSocket.SendStream( FSendStream);
接收数据并还原
procedure TMyClientContext.dataReceived(const pvDataObject: TObject);
var
lvMsgPack, lvMsgPack2:TSimpleMsgPack;
lvStream :TStream;
lvStream2:TMemoryStream;
vData:OleVariant;
lvResult:Boolean;
vMsg:String;
begin
lvMsgPack := TSimpleMsgPack.Create;
try
try
if FdmMain = nil then FdmMain := TdmMain.Create(nil);
lvStream := TStream(pvDataObject);
lvStream.Position := 0;
lvStream.Position := 0;
// unpack
lvMsgPack.DecodeFromStream(lvStream);
// get param
vData := lvMsgPack.ForcePathObject('cmd.data').AsVariant;
// invoke dataModule function
lvResult := FdmMain.Execute(lvMsgPack.ForcePathObject('cmd.index').AsInteger,
vData, vMsg);
// write result info
lvMsgPack.Clear;
lvMsgPack.ForcePathObject('__result.result').AsBoolean := lvResult;
lvMsgPack.ForcePathObject('__result.data').AsVariant := vData;
lvMsgPack.ForcePathObject('__result.msg').AsString := vMsg;
except
on E:Exception do
begin
lvMsgPack.Clear;
lvMsgPack.ForcePathObject('__result.result').AsBoolean := false;
lvMsgPack.ForcePathObject('__result.msg').AsString := e.Message;
end;
end;
lvStream.Size := 0;
lvMsgPack.EncodeToStream(lvStream);
lvStream.Position := 0;
// zipStream
TZipTools.compressStreamEX(lvStream);
lvStream.Position := 0;
// send to client
self.writeObject(lvStream);
finally
lvMsgPack.Free;
end;
end;