Table of Contents

Sending and receiving

Once connected, the client exchanges messages with the server: it sends text or binary frames and is notified of incoming ones through events. This chapter covers sending messages, receiving them, and working with binary data.

Sending messages

Call Send with a string to push a text frame to the server. Send only after OnConnect has fired; sending on a closed connection raises an error, so guard the send (for example by enabling the send button only while connected). This example pairs sending with the receive handler below.

procedure TForm1.SendChat(const AText: string);
begin
  // Send a text frame to the server.
  FClient.Send(AText);
end;

procedure TForm1.ClientMessageReceived(Sender: TObject;
  AConnection: TTMSFNCWebSocketConnection; const aMessage: string);
begin
  // Fires for every text message pushed by the server.
  Memo1.Lines.Add(aMessage);
end;

procedure TForm1.SendBytes(const AData: TBytes);
begin
  // The Send overload sends a binary frame; handle the peer's blobs in OnBinaryDataReceived.
  FClient.Send(AData);
end;

Receiving messages

Handle OnMessageReceived to process text the server pushes; it fires once per incoming text frame with the message string. A common pattern is to exchange JSON text — encode an object before Send and parse it in the handler — which lets a chat client carry a user name, message, and attachments in one frame.

Binary data

Send has an overload that takes TBytes for binary frames, and OnBinaryDataReceived delivers binary frames from the server. Use binary for file transfers and other non-text payloads rather than base64-encoding them into a text message.

Pitfalls

  • Send only while connected. Wrap sends in a connected check or catch the exception, as a dropped connection makes Send fail.
  • Match the message shape on both ends. If the server expects JSON, send JSON; there is no implicit framing of structured data.
  • Use the binary API for blobs. Large binaries sent as text waste bandwidth on encoding overhead.

See also