TsgcWebSocketClient | Client Open Connection

Once your client is configured to connect to a server, there are 3 different options to open a new connection.

 

Active Property

The easiest way to open a new connection is to set the Active property to true. This will attempt to connect to the server using the component configuration.

If you set the Active property to false, it will close the connection if active.

This method is executed in the same thread as the caller. So if you call it from the Main Thread, the method will be executed in the Main Thread of the application.

 

Open Connection


oClient := TsgcWebSocketClient.Create(nil);
...
oClient.Active := true;

When you call Active = true, you still cannot send any data to the server because the client may still be connecting. You must first wait until the OnConnect event is fired, and then you can start sending messages to the server.

 

 

Close Connection


oClient.Active := false;

When you call Active = false, you cannot be sure that connection is already closed just after this code, so you must wait until the OnDisconnect event is fired.

 

 

Start/Stop methods

When you call Start() or Stop() to connect/disconnect from the server, the call is executed in a secondary thread, so it does not block the thread where it is called. Use this method if you want to connect to a server and let your code below continue.

 

Open Connection


oClient := TsgcWebSocketClient.Create(nil);
...
oClient.Start();

When you call Start(), you still cannot send any data to the server because the client may still be connecting. You must first wait until the OnConnect event is fired, and then you can start sending messages to the server.

 

Close Connection


oClient.Stop();

When you call Stop(), you cannot be sure that connection is already closed just after this code, so you must wait until the OnDisconnect event is fired.

 

 

Connect/Disconnect methods

When you call Connect() or Disconnect() to open/close a connection to the server, the call is executed in the same thread where it is called, but it waits until the process is finished. You must set a Timeout to define the maximum time to wait until the process is finished (by default 10 seconds).

 

Example: connect to server and wait up to 5 seconds


oClient := TsgcWebSocketClient.Create(nil);
...
if oClient.Connect(5000) then
  oClient.WriteData('Hello from client')
else
  Error();

If the Connect() method returns a successful result, you can already send a message to the server because the connection is alive.

 

 

Example: disconnect from server and wait up to 10 seconds


if oClient.Disconnect(10000) then
  ShowMessage('Disconnected')
else
  ShowMessage('Not Disconnected');

If the Disconnect() method returns a successful result, this means that the connection is already closed.

 

OnBeforeConnect event can be used to customize the server connection properties before the client tries to connect to it.