Table of Contents

Connecting

TTMSFNCWebsocketClient opens a WebSocket connection to a server and exchanges messages over it. Connecting is a matter of pointing the client at a host and port, wiring the connection events, and calling Connect; a secure server adds TLS. This chapter covers addressing the server, opening and closing the connection, and connecting securely.

Setting the server address

Point the client at the server with HostName and Port — for a local server on port 5050, HostName := 'localhost' and Port := 5050. These must match the server's listening port (see Running a server).

Opening and closing the connection

Wire OnConnect and OnDisconnect, then call Connect. Connect is asynchronous — it returns immediately and raises OnConnect once the handshake completes, which is when it is safe to Send. Close the connection with Disconnect; pass ASendClose := True (the default) to send a proper close frame.

procedure TForm1.SetupClient;
begin
  FClient := TTMSFNCWebsocketClient.Create(Self);
  FClient.HostName := 'localhost';
  FClient.Port := 5050;

  FClient.OnConnect := ClientConnect;
  FClient.OnDisconnect := ClientDisconnect;
  FClient.OnMessageReceived := ClientMessageReceived;

  FClient.Connect; // opens the connection asynchronously
end;

procedure TForm1.ClientConnect(Sender: TObject; AConnection: TTMSFNCWebSocketConnection);
begin
  // Connected - it is now safe to Send.
  sendBtn.Enabled := True;
end;

procedure TForm1.ClientDisconnect(Sender: TObject; AConnection: TTMSFNCWebSocketConnection);
begin
  sendBtn.Enabled := False;
end;

To reach a wss:// server, set UseSSL := True before connecting. Set Origin when the server validates it. The TLS handshake then runs as part of Connect, and OnConnect still signals readiness.

Pitfalls

  • Send only after OnConnect. Connect returns before the handshake finishes; sending earlier fails.
  • Match UseSSL to the server. A plain client cannot connect to a wss:// server, and vice versa.
  • HostName/Port must match the server. A mismatch fails to connect rather than raising at assignment.

See also