TChilkatWebSocket Delphi ActiveX Reference Documentation

TChilkatWebSocket

Provides an API for implementing the client side of the WebSocket protocol.

Importing the Chilkat ActiveX into Delphi

Important: Whenever upgrading to a new version of Chilkat, make sure to re-imported ActiveX DLL into Delphi to regenerate the files described below.

Two things are required to use an ActiveX in Delphi:

  1. The ActiveX DLL needs to be registered via regsvr32 on the system where the Delphi application runs. See How To Register ActiveX DLLs for detailed information.
  2. The ActiveX component needs to be "imported". Use the Delphi Import Component Wizard to import the Chilkat type library. This creates the following files: Chilkat_v9_5_0_TLB.pas and Chilkat_v9_5_0_TLB.dcr. The Chilkat_v9_5_0_TLB.pas should be added to your project.

To import the Chilkat type library, do the following:

  1. In the Delphi RAD Studio, select the menu item "Component" --> "Import a Type Library".
  2. Find "Chilkat ActiveX v9.5.0" in the list and select it. This will only appear in the list if the ChilkatAx-9.5.0-win32.dll (or ChilkatAx-9.5.0-x64.dll) has been registered w/ regsvr32.
  3. Check the "Generate Component Wrappers" checkbox.
  4. Select a directory where the unit files (.pas and .dcr) will be generated.
  5. Select "Create Unit" and then "Finish".
  6. Add the .pas to your Delphi project.

To use a Chilkat ActiveX object in your Delphi code, add "Chilkat_v9_5_0_TLB" to the "uses" statement. For example:

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Chilkat_v9_5_0_TLB;

Object Creation

var
obj: TChilkatWebSocket;
...
begin
obj := TChilkatWebSocket.Create(Self);
...
// When finished, free the object instance.
obj.Free();

Properties

property CloseAutoRespond: Integer

Introduced in version 9.5.0.70

If 1, then a Close control frame is automatically sent in response to receiving a Close control frame (assuming that we did not initiate the Close in the first place). When the Close frame has both been received and sent, the underlying connection is automatically closed (as per the WebSocket protocol RFC specifications). Thus, if this property is 1, then two things automatically happen when a Close frame is received: (1) a Close frame is sent in response, and (2) the connection is closed.

The default value of this property is 1.

property CloseReason: WideString readonly

Introduced in version 9.5.0.70

The reason string received with the Close frame, if any.

property CloseReceived: Integer readonly

Introduced in version 9.5.0.70

If 1, then a Close frame was already received on this websocket connection. If CloseAutoRespond is 0, then an application can check this property value to determine if a Close frame should be sent in response.

property CloseStatusCode: Integer readonly

Introduced in version 9.5.0.70

The status code received with the Close frame. If no status code was provided, or no Close frame has yet been received, then this property will be 0.

property DebugLogFilePath: WideString

If set to a file path, causes each Chilkat method or property call to automatically append it's LastErrorText to the specified log file. The information is appended such that if a hang or crash occurs, it is possible to see the context in which the problem occurred, as well as a history of all Chilkat calls up to the point of the problem. The VerboseLogging property can be set to provide more detailed information.

This property is typically used for debugging the rare cases where a Chilkat method call hangs or generates an exception that halts program execution (i.e. crashes). A hang or crash should generally never happen. The typical causes of a hang are:

  1. a timeout related property was set to 0 to explicitly indicate that an infinite timeout is desired,
  2. the hang is actually a hang within an event callback (i.e. it is a hang within the application code), or
  3. there is an internal problem (bug) in the Chilkat code that causes the hang.

property FinalFrame: Integer readonly

Introduced in version 9.5.0.70

1 if the last data frame received by calling ReadFrame was a final frame. Otherwise 0.

property FrameDataLen: Integer readonly

Introduced in version 9.5.0.70

The number of bytes accumulated from one or more calls to ReadFrame. Accumulated incoming frame data can be retrieved by calling GetFrameData, GetFrameDataSb, or GetFrameDataBd.

property FrameOpcode: WideString readonly

Introduced in version 9.5.0.70

Indicates the type of frame received in the last call to ReadFrame. Possible values are "Continuation", "Text", "Binary", "Close", "Ping", or "Pong". Initially this property is set to the empty string because nothing has yet been received.

property FrameOpcodeInt: Integer readonly

Introduced in version 9.5.0.70

The integer value of the opcode (type of frame) received in the last call to ReadFrame. Possible values are:

0 - Continuation
1 - Text
2 - Binary
8 - Close
9 - Ping
10 - Pong

property IdleTimeoutMs: Integer

The maximum amount of time to wait for additional incoming data when receiving, or the max time to wait to send additional data. The default value is 30000 (30 seconds). This is not an overall max timeout. Rather, it is the maximum time to wait when receiving or sending has halted.

property IsConnected: Integer readonly

Introduced in version 9.5.0.70

Returns 1 if the websocket is connected. Otherwise returns 0.

property LastBinaryResult: OleVariant readonly

Introduced in version 9.5.0.52

The binary data returned by the last (binary data returning) method called. Only available if Chilkat.Global.KeepBinaryResult is set to 1. This provides a means for obtaining large varbinary results in the SQL Server environment (where limitations exist in getting large amounts of data returned by method calls, but where temp tables can be used for binary properties).

property LastErrorHtml: WideString readonly

Provides information in HTML format about the last method/property called. If a method call returns a value indicating failure, or behaves unexpectedly, examine this property to get more information.

property LastErrorText: WideString readonly

Provides information in plain-text format about the last method/property called. If a method call returns a value indicating failure, or behaves unexpectedly, examine this property to get more information.

Concept of LastErrorText

LastErrorText Standard Information

property LastErrorXml: WideString readonly

Provides information in XML format about the last method/property called. If a method call returns a value indicating failure, or behaves unexpectedly, examine this property to get more information.

property LastMethodSuccess: Integer

Introduced in version 9.5.0.52

Indicate whether the last method call succeeded or failed. A value of 1 indicates success, a value of 0 indicates failure. This property is automatically set for method calls. It is not modified by property accesses. The property is automatically set to indicate success for the following types of method calls:

  • Any method that returns a string.
  • Any method returning a Chilkat object, binary bytes, or a date/time.
  • Any method returning a standard boolean status value where success = 1 and failure = 0.
  • Any method returning an integer where failure is defined by a return value less than zero.

Note: Methods that do not fit the above requirements will always set this property equal to 1. For example, a method that returns no value (such as a "void" in C++) will technically always succeed.

property LastStringResult: WideString readonly

Introduced in version 9.5.0.52

The string return value of the last (string returning) method called. Only available if Chilkat.Global.KeepStringResult is set to 1. This provides a means for obtaining large string results in the SQL Server environment (where limitations exist in getting long strings returned by method calls, but where temp tables can be used for string properties).

Long Strings Returned by ActiveX Methods in SQL Server

property LastStringResultLen: Integer readonly

Introduced in version 9.5.0.53

The length, in characters, of the string contained in the LastStringResult property.

property NeedSendPong: Integer readonly

Introduced in version 9.5.0.70

If 1, then a Ping frame was received, but no Pong frame has yet been sent in response. The application should send a Pong frame by calling SendPong as soon as possible.

property PingAutoRespond: Integer

Introduced in version 9.5.0.70

If 1, then a Pong frame is automatically sent when a Ping frame is received. If set to 0, then the application may check the NeedSendPong property to determine if a Pong response is needed, and if so, may call the SendPong method to send a Pong.

Note: If this property is 1, then the ReadFrame method will auto-consume incoming Ping frames. In other words, ReadFrame will continue with reading the next incoming frame (thus Ping frames will never be returned to the application). This relieves the application from having to worry about receiving and handling spurious Ping frames.

The default value is 1.

property PongAutoConsume: Integer

Introduced in version 9.5.0.70

If 1, then incoming Pong frames are automatically consumed, and a call to ReadFrame will continue reading until it receives a non-Pong frame. The PongConsumed property can be checked to see if the last ReadFrame method call auto-consumed a Pong frame.

The default value is 1.

property PongConsumed: Integer readonly

Introduced in version 9.5.0.70

Is 1 if the last call to ReadFrame auto-consumed a Pong frame. This property is reset to 0 each time a ReadFrame method is called, and will get set to 1 if (1) the PongAutoConsume property is 1 and (2) a Pong frame was consumed within the ReadFrame method.

The purpose of PongAutoConsume and PongConsumed is to eliminate the concern for unanticipated Pong frames in the stream. In the websocket protocol, both sides (client and server) may send Pong frames at any time. In addition, if a Ping frame is sent, the corresponding Pong response frame can arrive at some unanticipated point later in the conversation. It's also possible, if several Ping frames are sent, that a Pong response frame is only sent for the most recent Ping frame. The default behavior of Chilkat's WebSocket API is to auto-consume incoming Pong frames and set this property to 1. This allows the application to call a ReadFrame method for whatever application data frame it may be expecting, without needing to be concerned if the next incoming frame is a Pong frame.

property ReadFrameFailReason: Integer readonly

Introduced in version 9.5.0.70

If the ReadFrame method returns 0, this property holds the fail reason. It can have one of the following values:

0 - No failure.
1 - Read Timeout.
2 - Aborted by Application Callback.
3 - Fatal Socket Error (Lost Connection).
4 - Received invalid WebSocket frame bytes.
99 - A catch-all for any unknown failure.  (Should not ever occur.  If it does, contact Chilkat.)

property VerboseLogging: Integer

If set to 1, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is 0. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

property Version: WideString readonly

Version of the component/library, such as "9.5.0.63"

Methods

function AddClientHeaders(): Integer;

Introduced in version 9.5.0.70

Adds the required WebSocket client-side open handshake headers. The headers specifically added to the previously specified REST object (in the call to UseConnection) are:

Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: ...
Sec-WebSocket-Version: 13

Returns 1 for success, 0 for failure.

WebSocket Connect

function CloseConnection(): Integer;

Introduced in version 9.5.0.70

Forcibly closes the underlying connection. This is a non-clean way to close the connection, but may be used if needed. The clean way to close a websocket is to send a Close frame, and then receive the Close response.

Returns 1 for success, 0 for failure.

function GetFrameData(): WideString;

Introduced in version 9.5.0.70

Returns the accumulated received frame data as a string. Calling GetFrameData clears the internal receive buffer.

Returns a zero-length WideString on failure

function GetFrameDataBd(binData: TChilkatBinData): Integer;

Introduced in version 9.5.0.70

Returns the accumulated received frame data in a BinData object. The received data is appended to the binData.

Calling this method clears the internal receive buffer.

WebSocket Send/Receive Binary Data

function GetFrameDataSb(sb: TChilkatStringBuilder): Integer;

Introduced in version 9.5.0.70

Returns the accumulated received frame data in a StringBuilder object. The received data is appended to the sb.

Calling this method clears the internal receive buffer.

function PollDataAvailable(): Integer;

Introduced in version 9.5.0.70

Check to see if data is available for reading on the websocket. Returns 1 if data is waiting and 0 if no data is waiting to be read.

function ReadFrame(): Integer;

Introduced in version 9.5.0.70

Reads a single frame from the connected websocket. If a frame was successfuly received, then the following properties are set: FrameOpcode, FrameDataLen, FinalFrame, and the received frame data can be retrieved by calling GetFrameData, GetFrameDataSb, or GetFrameDataBd.

Returns 1 for success, 0 for failure.

Send and Receive WebSocket Frame

Send and Receive WebSocket Messages

function ReadFrameAsync(): TChilkatTask;

Introduced in version 9.5.0.70

Creates an asynchronous task to call the ReadFrame method with the arguments provided. (Async methods are available starting in Chilkat v9.5.0.52.)

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

How to Run an Asynchronous Task

function SendClose(includeStatus: Integer; statusCode: Integer; reason: WideString): Integer;

Introduced in version 9.5.0.70

Sends a Close control frame. If includeStatus is 1, then the statusCode is sent in the application data part of the Close frame. A Close reason may be provided only if includeStatus is 1. If this Close was sent to satisfy an already-received Close frame, then the underlying connection will also automatically be closed.

Note: If a status code and reason are provided, the utf-8 representation of the reason string must be 123 bytes or less. Chilkat will automatically truncate the reason to 123 bytes if necessary. Also, the status code must be an integer in the range 0 to 16383.

The WebSocket protocol specifies some pre-defined status codes at WebSocket Status Codes. For a normal closure, a status code value of 1000 should be used. The reason can be any string, as long as it is 123 bytes or less.

Returns 1 for success, 0 for failure.

function SendCloseAsync(includeStatus: Integer; statusCode: Integer; reason: WideString): TChilkatTask;

Introduced in version 9.5.0.70

Creates an asynchronous task to call the SendClose method with the arguments provided. (Async methods are available starting in Chilkat v9.5.0.52.)

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

How to Run an Asynchronous Task

function SendFrame(stringToSend: WideString; finalFrame: Integer): Integer;

Introduced in version 9.5.0.70

Sends a single data frame containing a string. If this is the final frame in a message, then finalFrame should be set to 1. Otherwise set finalFrame equal to 0.

Returns 1 for success, 0 for failure.

Send and Receive WebSocket Frame

Send and Receive WebSocket Messages

function SendFrameAsync(stringToSend: WideString; finalFrame: Integer): TChilkatTask;

Introduced in version 9.5.0.70

Creates an asynchronous task to call the SendFrame method with the arguments provided. (Async methods are available starting in Chilkat v9.5.0.52.)

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

How to Run an Asynchronous Task

function SendFrameBd(bdToSend: TChilkatBinData; finalFrame: Integer): Integer;

Introduced in version 9.5.0.70

Sends a single data frame containing binary data (the contents of bdToSend). If this is the final frame in a message, then finalFrame should be set to 1. Otherwise set finalFrame equal to 0.

Returns 1 for success, 0 for failure.

WebSocket Send/Receive Binary Data

function SendFrameBdAsync(bdToSend: TChilkatBinData; finalFrame: Integer): TChilkatTask;

Introduced in version 9.5.0.70

Creates an asynchronous task to call the SendFrameBd method with the arguments provided. (Async methods are available starting in Chilkat v9.5.0.52.)

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

How to Run an Asynchronous Task

function SendFrameSb(sbToSend: TChilkatStringBuilder; finalFrame: Integer): Integer;

Introduced in version 9.5.0.70

Sends a single data frame containing a string (the contents of sbToSend). If this is the final frame in a message, then finalFrame should be set to 1. Otherwise set finalFrame equal to 0.

Returns 1 for success, 0 for failure.

function SendFrameSbAsync(sbToSend: TChilkatStringBuilder; finalFrame: Integer): TChilkatTask;

Introduced in version 9.5.0.70

Creates an asynchronous task to call the SendFrameSb method with the arguments provided. (Async methods are available starting in Chilkat v9.5.0.52.)

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

How to Run an Asynchronous Task

function SendPing(pingData: WideString): Integer;

Introduced in version 9.5.0.70

Sends a Ping control frame, optionally including text data. If pingData is non-empty, the utf-8 representation of the string must be 125 bytes or less. Chilkat will automatically truncate the pingData to 125 bytes if necessary.

Returns 1 for success, 0 for failure.

Send a WebSocket Ping Control Frame

function SendPingAsync(pingData: WideString): TChilkatTask;

Introduced in version 9.5.0.70

Creates an asynchronous task to call the SendPing method with the arguments provided. (Async methods are available starting in Chilkat v9.5.0.52.)

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

How to Run an Asynchronous Task

function SendPong(): Integer;

Introduced in version 9.5.0.70

Sends a Pong control frame. If this Pong frame is sent to satisfy an unresponded-to Ping frame, then the previously received Ping data is automatically sent in this Pong frame.

Returns 1 for success, 0 for failure.

function SendPongAsync(): TChilkatTask;

Introduced in version 9.5.0.70

Creates an asynchronous task to call the SendPong method with the arguments provided. (Async methods are available starting in Chilkat v9.5.0.52.)

Note: Async method event callbacks happen in the background thread. Accessing and updating UI elements existing in the main thread may require special considerations.

Returns nil on failure

How to Run an Asynchronous Task

function UseConnection(connection: TChilkatRest): Integer;

Introduced in version 9.5.0.70

Initializes the connection for a WebSocket session. All WebSocket sessions begin with a call to UseConnection. A Chilkat REST object is used for the connection because the WebSocket handshake begins with an HTTP GET request. The Chilkat REST API provides the ability to add custom headers, authentication, etc. to the opening GET handshake. It also provides the ability to establish connections over TLS or SSH and to benefit from the rich set of features already present relating to HTTP proxies, SOCKS proxies, bandwidth throttling, IPv6, socket options, etc.

Returns 1 for success, 0 for failure.

WebSocket Connect

WebSocket over TLS

WebSocket through SSH Tunnel

function ValidateServerHandshake(): Integer;

Introduced in version 9.5.0.70

Called after sending the opening handshake from the Rest object. Validates the server's response to the opening handshake message. If validation is successful, the application may begin sending and receiving data and control frames.

Returns 1 for success, 0 for failure.

WebSocket Connect

Events

procedure AbortCheck(ASender: TObject; out abort: Integer);

Provides the opportunity for a method call to be aborted. The AbortCheck event is fired periodically based on the value of the HeartbeatMs property. If HeartbeatMs is 0, then no AbortCheck events will fire. As an example, to fire 5 AbortCheck events per second, set the HeartbeatMs property equal to 200.

Delphi ActiveX Event callback implementation:

procedure TForm1.websocketAbortCheck(ASender: TObject;  out abort: Integer);
begin
    // Application code goes here...
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  websocket: TChilkatWebSocket;

begin
  websocket := TChilkatWebSocket.Create(Self);
  websocket.OnAbortCheck := websocketAbortCheck;
  // ...

procedure BinaryData(ASender: TObject; data: OleVariant; length: Integer);

Binary data provided by certain methods.

Delphi ActiveX Event callback implementation:

procedure TForm1.websocketBinaryData(ASender: TObject;  data: OleVariant; length: Integer);
begin
    // Application code goes here...
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  websocket: TChilkatWebSocket;

begin
  websocket := TChilkatWebSocket.Create(Self);
  websocket.OnBinaryData := websocketBinaryData;
  // ...

procedure PercentDone(ASender: TObject; pctDone: Integer; out abort: Integer);

Provides the percentage completed for any method that involves network communications or time-consuming processing (assuming it is a method where a percentage completion can be measured). This event is only fired when it is possible to know a percentage completion, and when it makes sense to express the operation as a percentage completed. The pctDone argument will have a value from 1 to 100. For operations (Chilkat method calls) that complete very quickly, the number of PercentDone callbacks will vary, but the final callback should have a value of 100. For long running operations, no more than one callback per percentage point will occur (for example: 1, 2, 3, ... 98, 99, 100).

The PercentDone callback counts as an AbortCheck event. For method calls that complete quickly such that PercentDone events fire, it may be that AbortCheck events don't fire because the opportunity to abort is already provided in the PercentDone callback. For time consuming operations, where the amount of time between PercentDone callbacks are long, AbortCheck callbacks may be used to allow for the operation to be aborted in a more responsive manner.

The abort output argument provides a means for aborting the operation. Setting it to 1 will cause the method to abort and return a failed status (or whatever return value indicates failure).

Delphi ActiveX Event callback implementation:

procedure TForm1.websocketPercentDone(ASender: TObject;  pctDone: Integer; out abort: Integer);
begin
    // Application code goes here...
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  websocket: TChilkatWebSocket;

begin
  websocket := TChilkatWebSocket.Create(Self);
  websocket.OnPercentDone := websocketPercentDone;
  // ...

procedure ProgressInfo(ASender: TObject; const name: WideString; const value: WideString);

A general name/value event that provides information about what is happening during a method call. To find out what information is available, write code to handle this event and log the name/value pairs. Most are self-explanatory.

Delphi ActiveX Event callback implementation:

procedure TForm1.websocketProgressInfo(ASender: TObject;  const name: WideString; const value: WideString);
begin
    // Application code goes here...
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  websocket: TChilkatWebSocket;

begin
  websocket := TChilkatWebSocket.Create(Self);
  websocket.OnProgressInfo := websocketProgressInfo;
  // ...

procedure TaskCompleted(ASender: TObject; const task: IChilkatTask);

Called in the background thread when an asynchronous task completes.

Delphi TaskCompleted Event Callback Example

Delphi ActiveX Event callback implementation:

procedure TForm1.websocketTaskCompleted(ASender: TObject;  const task: IChilkatTask);
begin
    // Application code goes here...
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  websocket: TChilkatWebSocket;

begin
  websocket := TChilkatWebSocket.Create(Self);
  websocket.OnTaskCompleted := websocketTaskCompleted;
  // ...

procedure TextData(ASender: TObject; const data: WideString);

Text data provided by certain methods.

Delphi ActiveX Event callback implementation:

procedure TForm1.websocketTextData(ASender: TObject;  const data: WideString);
begin
    // Application code goes here...
end;


procedure TForm1.Button1Click(Sender: TObject);
var
  websocket: TChilkatWebSocket;

begin
  websocket := TChilkatWebSocket.Create(Self);
  websocket.OnTextData := websocketTextData;
  // ...