设置
IdTCPServer1.DefaultPort := 10001;
IdTCPServer1.Active := True;
IdTCPClient1.Host := '服务端地址'
IdTCPClient1.Port := 10001;
if not IdTCPClient1.Connected then
IdTCPClient1.Connect
1. 客户端发送:
procedure TForm1.Button1Click(Sender: TObject);
begin
IdTCPClient1.WriteLn('ok');
end;
2. 服务端接收:
procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
var
s: string;
begin
s := AThread.Connection.ReadLn;
end;
3.. 客户端接收数据
用线程
TReceiveThread = class(TThread)
private
FMsg: string;
protected
procedure Execute; override;
end;
var
FThread: TReceiveThread;
procedure TReceiveThread.Execute;
begin
while not Terminated do
begin
if Form1.IdTCPClient1.Connected then
begin
FMsg := Form1.IdTCPClient1.ReadLn;
Sleep(100);
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FThread := TReceiveThread.Create(False);
IdTCPClient1.Host := Edit1.Text;
IdTCPClient1.Port := 10001;
if not IdTCPClient1.Connected then
IdTCPClient1.Connect;
end;
2. 服务端发送数据
procedure TForm1.SpeedButton1Click(Sender: TObject);
var
i : Integer;
AThread : TIdPeerThread;
begin
try
with IdTCPServer1.Threads.LockList do
for I := 0 to Count - 1 do
begin
AThread := Items
;
if AThread.Connection.Socket.Binding.PeerIP = 'hostname' then
AThread.Connection.WriteLn(s);
end;
finally
IdTCPServer1.Threads.UnlockList;
end;
end;