Broadcasting messages
A chat-style server rarely replies only to the sender — it relays each message to
the other connected clients. TTMSFNCWebSocketServer does this with
SendMessageTo, which sends a message to every client that a selector function
accepts. This chapter covers relaying messages between clients and targeting a
subset of them.
Relaying messages between clients
Handle OnMessageReceived and call SendMessageTo with the text and a selector.
The selector runs once per connected client and returns True for those that
should receive the message — returning True for everyone except the sender
produces the classic broadcast. This example combines receiving a message with
broadcasting it to the other clients.
procedure TForm1.ServerMessageReceived(Sender: TObject;
AConnection: TTMSFNCWebSocketConnection; const aMessage: string);
begin
// SendMessageTo broadcasts; the selector decides which clients receive it.
// Here every client except the original sender gets the message.
FServer.SendMessageTo(aMessage,
function(AClientConnection: TTMSFNCWebSocketServerConnection): Boolean
begin
Result := AClientConnection <> AConnection;
end);
end;
Targeting specific clients
Because the selector is a function of the client connection, you can route
messages however you like: compare against a stored connection to send privately,
keep a map of connections to user names to implement direct messages, or return
True for all to reach everyone. The AConnection passed to OnMessageReceived
identifies the sender, and each TTMSFNCWebSocketServerConnection passed to the
selector identifies a recipient.
Pitfalls
- The selector runs for every client. Keep it cheap; it is called once per connection on each broadcast.
- Hold connection references carefully. A stored connection becomes invalid
after that client disconnects — clear it in
OnDisconnect. - Messages are strings here; use the binary API for blobs. Large files are better sent as binary data than as an encoded string.
See also
- Running a server — start the server and wire its events.
- API reference — full class reference.