用IdTcpClient和IdTcpServer是可以多线程收发Stream的。
Client用一个线程负责收发,可以使用Idthreadcomponent控件
procedure TForm.TcpClientThreadRun(Sender: TIdCustomThreadComponent);
var
Adata:TmemoryStream;
begin
AData:=TmemoryStream.Create;
if assigned(Adata) then begin
if Tcpclient.Connected then begin
Adata.Clear;
try
// ....Adata.write(.....)
Adata.Position:=0;
tcpclient.WriteStream(Adata,true,true.0);
tcpclient.ReadStream(Adata,-1,false);
//.......注意ReadStream的参数-1表示接收所有数据(他会先接收数据包的大小)
//.......发送用WriteStream(Adata,true,true,0);
//.......注意处理数据前最好让Adata.Position:=0;
except
on e:exception do begin
tcpclient.Disconnect;
end;
end;
end else begin
try
Tcpclient.Connect(1000);
except
end;
end;
end;
Adata.Free;
end;
服务端在IdTcpServer的Execute里面处理
procedure TForm.TCPServerExecute(AThread: TIdPeerThread);
var
Adata:TmemoryStream;
begin
Adata:=TmemoryStream.Create;
try
adata.Clear;
Athread.Connection.ReadStream(Adata,-1,false);
Adata.position:=0;
Athread.connection.writestream(Adata,true,true,0);
//.....发送用Write(Adata,true,true,0)
//...注意读取数据前最好让Adata.Position:=0;
except
Athread.Connection.Disconnect;
end;
Adata.Free;
end;