Question

I would like to know a good approach to handle "one to many" communication using Indy 10 TidTCPServer ie receive a stream from a client, and immediately write this data to all connected "viewers". The point here is that the source of the data comes from a client (not the server).

On the OnExecute procedure, I can't write to other connected clients from there and using LockList just freezes the current thread so it doesn't help...

Should I use a different thread to handle buffer exchange?

Buffer data is mainly bytes, clients are already connected, let's say 3 (#1 sends, #2 and #3 should receive)

Here's what's in my OnExecute procedure:

var
lst: Tlist;

[­..]

  lst := idTcpServer1.Contexts.LockList;

  try
    for i := 1 to lst.Count-1 do
    begin
      try
        TIdContext(lst.Items[i]).Connection.IOHandler.Write('Test');
      except
      end;
    end;
  finally
    idTcpServer1.Contexts.UnlockList;
  end;
Was it helpful?

Solution

TCP does not support broadcasting, you have to use UDP or Multicast for that. So your only option is to loop through the Contexts list each time you have something to send.

You can certainly do that in the OnExecute event, if you don't mind slowing down the sending client. Assuming you do not want to do that, then yes, you have to move the loop to another thread. You could have the OnExecute handler put each received block of data into a thread-safe queue and then have the broadcasting thread extract data from the queue and send it to connected clients as needed.

As an added measure, you could also give each client its own individual thread-safe queue for outbound data, have the broadcast thread (or even OnExecute directly) put each block of data into each client's queue, then have the OnExecute event push a client's queue to the client when its not busy doing something else. That way, broadcasting and sending of data blocks is done in parallel so any given client does not block any other clients from receiving data in a timely manner, since each client runs in its own thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top