客户端IdTCPClient向服务端IdTCPServer1发送消息
客户端IdTCPClient向服务端IdTCPServer1发送消息
1、连接
with IdTCPServer1 do
begin
Bindings.Clear;
Bindings.Add.IP := '127.0.0.1';
Bindings.Add.Port := 1982;
Active := True;
end;
with IdTCPClient1 do
begin
Host := '127.0.0.1';
Port := 1982;
Connect;
end;
2、服务端向客户端发消息
procedure TForm1.BtnSendClick(Sender: TObject);
var
I: Integer;
LContext: TIdContext;
begin
IdTCPServer1.Contexts.LockList;
with IdTCPServer1.Contexts.LockList do
begin
try
for i := 0 to Count - 1 do
begin
LContext := IdTCPServer1.Contexts.LockList[i];
LContext.Connection.IOHandler.WriteLn('stwo');
//上面是向所有的客户端发送消息,我们也可以利用用下面两个属性向指定的客户端发送消息
//LContext.Connection.Socket.Binding.PeerIP;//客户端IP,
//LContext.Connection.Socket.Binding.Port;//客户端Port
end;
finally
IdTCPServer1.Contexts.UnlockList;
end;
end;
end;
3、读取客户端发送的消息
if IdTCPClient1.IOHandler.Readable(1) then //检查是否有可读取的消息或服务端是否已关闭
ShowMessage(IdTCPClient1.IOHandler.ReadLn());