For a simple TCP server look at the echo demo that comes with synapse in the demos directory.
Don't know where you got your code from but it would be a nice example of how not to do it
First, before writing the first line of code, acquire some basic have to know knowledge on sockets:
http://en.wikipedia.org/wiki/Berkeley_sockets- ListenerSocket.bind('192.168.1.103','12345') : here you bind to one interface only, the one that has address '192.168.1.103'. Typically you'll want to listen on all interfaces. Use ListenerSocket.bind('0.0.0.0','12345')
- After a bind, listen is called to start accepting tcp connections. When an incoming connection is detected, the socket is signaled and the accept routine creates a new socket for the accepted connection. You have to use this new socket to handle the communication. So in short a server loop should look like this:
var
ClientSock: TSocket;
sock: TTCPBlockSocket;
begin
sock := TTCPBlockSocket.Create;
try
sock.bind('0.0.0.0','12345');
sock.listen;
if sock.LastError <> 0 then
exit;
while not terminated do
begin
if sock.canread(1000) then
begin
ClientSock := sock.accept;
if sock. lastError = 0 then
TalkToClient(ClientSock);
end;
end;
finally
sock.Free;
end;
end;
If you want to accept only one connection at a time, TalkToClient can be a simple procedure. If you want multiple simultaneous connections, TalkToClient will have to hand over the ClientSock communication processing to a separate thread and return immediately. In both cases, the communication processing looks like this:
var
s: string;
begin
sock:=TTCPBlockSocket.create;
try
Sock.socket:=ClientSock ;
sock.GetSins;
with sock do
begin
repeat
if client_terminated then break;
s := RecvPacket(60000);
if lastError<>0 then break;
//create reply
SendString(s);
if lastError<>0 then break;
until false;
end;
finally
Sock.Free;
end;
end;
Client_terminated is a boolean var used to close the connection from server side. A socket closed by the client will be detected by the lastError<>0 tests.
I repeat, look at the 'echo' demo in synapse. It is the simplest TCP server you can imagine that runs in the background and accepts multiple simultaneous connections.