我正在尝试使用我在通过网络发送之前转换为流的集合在IdTCPServer和IdTCPClient之间交换数据。不幸的是,无论我如何尝试,我似乎无法在客户端和服务器之间传递流。代码始终挂在 IdTCPClient1.IOHandler.ReadStream(myStream,-1,True)行上。
我的代码的相关部分如下所示:
客户端
with ClientDataModule do
begin
try
try
intStreamSize := StrToInt(IdTCPClient1.IOHandler.ReadLn); // Read stream size
IdTCPClient1.IOHandler.ReadStream(myStream, -1, True); // Read record stream
finally
ReadCollectionFromStream(TCustomer, myStream);
end;
except
ShowMessage('Unable to read the record from stream');
end;
end;
服务器端
try
try
SaveCollectionToStream(ACustomer, MStream);
finally
MStream.Seek(0, soFromBeginning);
IOHandler.WriteLn(IntToStr(MStream.Size)); // Send stream size
IOHandler.Write(MStream, 0); // Send record stream
end;
except
ShowMessage('Unable to save the record to stream');
end;
非常感谢您协助解决此问题。
谢谢,
JDaniel
答案 0 :(得分:1)
您正在将AReadUntilDisconnect
ReadStream()
参数设置为True,这表示在连接关闭之前一直保持读数。您需要将参数设置为False。您还需要在AByteCount
参数中传入流大小,因为您要单独发送流大小,因此您必须告诉ReadStream()
实际读取了多少。
试试这个:
客户端:
with ClientDataModule do
begin
try
intStreamSize := StrToInt(IdTCPClient1.IOHandler.ReadLn);
IdTCPClient1.IOHandler.ReadStream(myStream, intStreamSize, False);
myStream.Position := 0;
ReadCollectionFromStream(TCustomer, myStream);
except
ShowMessage('Unable to read the record from stream');
end;
end;
服务器:
try
SaveCollectionToStream(ACustomer, MStream);
MStream.Position := 0;
IOHandler.WriteLn(IntToStr(MStream.Size));
IOHandler.Write(MStream);
except
ShowMessage('Unable to save the record to stream');
end;
如果您可以更改协议,则可以让Write()
和ReadStream()
在内部为您交换流大小,如下所示:
客户端:
with ClientDataModule do
begin
try
// set to True to receive a 64bit stream size
// set to False to receive a 32bit stream stream
IdTCPClient1.IOHandler.LargeStream := ...;
IdTCPClient1.IOHandler.ReadStream(myStream, -1, True);
myStream.Position := 0;
ReadCollectionFromStream(TCustomer, myStream);
except
ShowMessage('Unable to read the record from stream');
end;
end;
服务器:
try
SaveCollectionToStream(ACustomer, MStream);
MStream.Position := 0;
// set to True to send a 64bit stream size
// set to False to send a 32bit stream stream
IOHandler.LargeStream := ...;
IOHandler.Write(MStream, 0, True);
except
ShowMessage('Unable to save the record to stream');
end;