indy10 TCP实例
先来个TCP的:
放两个TMemo,分别叫:Memo_Input, Memo_out 一个输入,一个输出
IdTCPServer1的Bindings里,设置 0.0.0.0:3999,Actibve
IdTCPClient1的Port设3999
发送按钮的代码:
var
bufSend: TMemoryStream;
begin
try
//连接
IdTCPClient1.Connect(Edit_IP.Text);
except
Memo_out.Lines.Add(Edit_IP.Text+' 连接超时!'); Exit;
end;
//准备发送
bufSend:=TMemoryStream.Create;
try
Memo_Input.Lines.SaveToStream(bufSend);
IdTCPClient1.IOHandler.Write(bufSend); //发送流
finally
IdTCPClient1.Disconnect; //关闭连接
bufSend.Free;
end;
end;
服务器IdTCPServer1的OnExecute事件:
//注意要uses IdContext
procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var
bufRecv: TMemoryStream;
begin
if Not(AContext.Connection.Connected) then Exit; //未连接时退出
bufRecv:=TMemoryStream.Create;
try
//一直接收 直到连接断开
while AContext.Connection.Connected do
begin
AContext.Connection.IOHandler.ReadStream(bufRecv, -1, True);
end;
//数据接收完毕
bufRecv.Seek(0, soFromBeginning);
Memo_out.Lines.LoadFromStream(bufRecv);
finally
bufRecv.Free;
end;
end;