Once your client is configured to connect to server, there are 3 different options to call Open a new connection.
The most easy way to open a new connection is Set Active property to true. This will try to connect to server using component configuration.
If you set Active property to false, will close connection if active.
This method is executed in the same thread that caller. So if you call in the Main Thread, method will be executed in Main Thread of application.
Open Connection
oClient := TsgcWebSocketClient.Create(nil);
...
oClient.Active := true;
When you call Active = true, you can't still send any data to server because client maybe is still connecting, you must first wait to OnConnect event is fired and then you can start to send messages to 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 to OnDisconnect event is fired.
When you call Start() or Stop() to connect/disconnect from server, is executed in a secondary thread, so it doesn't blocks the thread where is called. Use this method if you want connect to a server and let your code below continue.
Open Connection
oClient := TsgcWebSocketClient.Create(nil);
...
oClient.Start();
When you call Start(), you can't still send any data to server because client maybe is still connecting, you must first wait to OnConnect event is fired and then you can start to send messages to 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 to OnDisconnect event is fired.
When you call Connect() or Disconnect() to open/close connection from server, this is executed in the same thread where is called, but it waits till process is finished. You must set a Timeout to set the maximum time to wait till process is finished (by default 10 seconds)
Example: connect to server and wait till 5 seconds
oClient := TsgcWebSocketClient.Create(nil);
...
if oClient.Connect(5000) then
oClient.WriteData('Hello from client')
else
Error();
If after calling Connect() method, the result is successful, you can already send a message to server because connection is alive.
Example: connect to server and wait till 10 seconds
if oClient.Disconnect(10000) then
ShowMessage('Disconnected')
else
ShowMessage('Not Disconnected');
If after calling Disconnect() event the result is successful, this means that connection is already closed.
OnBeforeConnect event can be used to customize the server connection properties before the client tries to connect to it.