我试图在IdTCPServer和IdTCPClient之间交换数据,使用我在通过网络发送之前转换为流的集合。不幸的是,无论我如何尝试,我似乎都无法在客户端和服务器之间传递流。代码总是挂在IdTCPClient1.IOHandler上。ReadStream(myStream, -1, True) line。
我的代码的相关部分如下所示: 客户端 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
您正在将ReadStream()
的AReadUntilDisconnect
参数设置为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;