I am using Synapse with blocking sockets and try to simply send text to the connected client. Here comes the code:
var
SServer: TTCPBlockSocket;
SClient: TTCPBlockSocket;
implementation
//Create and initialize the Sockets.
procedure TForm1.FormCreate(Sender: TObject);
begin
SClient := TTCPBlockSocket.Create;
SServer := TTCPBlockSocket.Create;
SServer.Bind('127.0.0.1', '12345');
SClient.Connect('127.0.0.1', '12345');
end;
//Wait for connections.
procedure TForm1.FormShow(Sender: TObject);
begin
SServer.Accept;
//SServer.Listen; <- Could also work here?
end;
//Send the string to the connected server.
procedure TForm1.Button3Click(Sender: TObject);
begin
SClient.SendString('hi server');
end;
//Receive the string from the client with timeout 1000ms and write it into a memo
procedure TForm1.Button2Click(Sender: TObject);
var buf: string;
begin
Memo1.Lines.Add(SServer.RecvString(1000));
end;
First, I click Button 3, then I click Button2. Doing so, there is nothing getting written inside the memo1 field.
Shouldn't this work?
#
****EDIT:****
#
According to skramads comment, I have now split it up into 2 programs. Here we go:
Client:
var
SClient: TTCPBlockSocket;
implementation
procedure TForm2.Button1Click(Sender: TObject);
begin
SClient.SendString(Edit1.Text);
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
SClient := TTCPBlockSocket.Create;
end;
procedure TForm2.FormShow(Sender: TObject);
begin
SClient.Connect('127.0.0.1','12345');
end;
Server:
var
Form1: TForm1;
SSocket: TTCPBlockSocket;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
SSocket.Bind('127.0.0.1','12345');
SSocket.Listen;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Memo1.Lines.Add(SSocket.RecvString(1000));
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SSocket := TTCPBlockSocket.Create;
end;
Still, this does not work as intended. I just get no data over there.
Any ideas?
You should read how socket communications work, for example here (English) or here (German). In short: the socket you
listen()
on on the server side is not used for the communication itself, you have to callaccept()
to open another socket as the partner for the client, and use that one to send and receive data. The listening socket is used solely to accept other connections from other clients, which you can then use to communicate between one server and several clients in parallel.Maybe you should first examine a simple client/server demo application. The principles are the same, whether you use Synapse, Indy or low-level API programming.
if you break this into two separate programs, then it will work better. Blocking calls do just that...they block until they complete.