I have 2 forms, 1 for server another for client. After dropping ttcpserver on server form and setting its localhost property to 127.0.0.1 and localport property to 55555 and Active property to true I wrote a button1(sendtextbutton) onclick event handler:
procedure TForm2.Button1Click(Sender: TObject);
begin
TcpServer1.Sendln('message');
end;
Then on client form I dropped 1 ttcpclient 1 label 2 buttons, set clients remote host property to 127.0.0.1 and remote port to 55555, wrote an event handler for connectbutton(button1):
procedure TForm2.Button1Click(Sender: TObject);
begin
try
TcpClient1.Active := true;
except
showmessage('error');
end;
end;
Wrote an onconnect event for ttcpclient:
procedure TForm2.TcpClient1Connect(Sender: TObject);
begin
Label1.Caption := 'connected!';
end;
and then finally an onrecieve event hadler for ttcpclient:
procedure TForm2.TcpClient1Receive(Sender: TObject; Buf: PAnsiChar;
var DataLen: Integer);
begin
Label1.caption := TcpClient1.Receiveln();
end;
My client programs caption was supposed to change to 'message'(after I connect and click button on my server form), but it doest. Am I doing it the wrong way? If yes, then how to do it? I am trying to send a text message from server to client(Yes a reverse connection!)
TTcpServer does not store a list of connected connection which make broadcast style messages difficult.
I would recommend switching to TidTcpServer and TidTcpClient. The TidTcpServer component has a Context Property that you can loop through to broadcast messages to the clients similar to what you seem to want to do.
Here some links to examples of using TidTcpServer and TIdTcpClient: