Table of Contents

Running a server

TTMSFNCWebSocketServer accepts WebSocket clients and exchanges messages with them. Running one is a matter of choosing a port, wiring the connection events, and setting the server active; securing it adds a TLS certificate. This chapter covers the server lifecycle and how to run it over a secure connection.

Starting and stopping

Set Port, wire the events you care about (OnConnect, OnDisconnect, OnMessageReceived), and set Active := True to begin listening. Setting Active := False stops the server and disconnects clients. The server is asynchronous: once active, its events fire as clients connect and send data.

procedure TForm1.StartServer;
begin
  FServer := TTMSFNCWebSocketServer.Create(Self);
  FServer.Port := 5050;

  FServer.OnConnect := ServerConnect;
  FServer.OnDisconnect := ServerDisconnect;
  FServer.OnMessageReceived := ServerMessageReceived;

  FServer.Active := True; // begin listening for clients
end;

procedure TForm1.StopServer;
begin
  FServer.Active := False;
end;

procedure TForm1.ServerConnect(Sender: TObject; AConnection: TTMSFNCWebSocketConnection);
begin
  Log('A client connected');
end;

procedure TForm1.ServerDisconnect(Sender: TObject; AConnection: TTMSFNCWebSocketConnection);
begin
  Log('A client disconnected');
end;

Securing with TLS

To serve over wss://, set UseSSL := True and supply the certificate files: CertificateFile, CertificateKeyFile, and (when needed) RootCertificateFile. Provide the key password through OnGetSSLPassword. Clients must then connect with their own UseSSL enabled.

Pitfalls

  • Set the port and events before Active := True. Changing the port while active has no effect until the server is restarted.
  • Free or deactivate the server on shutdown. Leaving it active can hold the listening socket open.
  • A blocked port fails silently to clients. Ensure the chosen Port is open in the firewall.

See also