---
product: Chilkat
product_version: 11.7.0
language: pascal
language_label: Lazarus Pascal
class: WebSocket
license: bundle
deprecated: false
reference_html: https://www.chilkatsoft.com/refdoc/pascal_WebSocketRef.html
---
# Chilkat WebSocket — Lazarus Pascal — v11.7.0

> Chilkat 11.7.0 · language=pascal · class=WebSocket
> Other versions: replace `11.7.0` in this URL. Other languages: `https://www.chilkatsoft.com/ai-docs/v/11.7.0/<lang>/classes/WebSocket.md`.
> Language-wide rules (install, unlock, error model, strings/bytes): `https://www.chilkatsoft.com/ai-docs/v/11.7.0/pascal/guide.md`.

## Purpose

**Connect to WebSocket servers and exchange client-side frames and messages.**

**Client-side only:** `Chilkat.WebSocket` implements the client side of the WebSocket protocol. It initiates an opening handshake with an existing WebSocket server. It does not listen for incoming connections, accept clients, or implement a WebSocket server.

`Chilkat.WebSocket` operates over an established `Chilkat.Rest` connection. It creates and validates the HTTP upgrade handshake, sends and receives text or binary frames, supports fragmented messages, handles Ping, Pong, and Close control frames, polls for incoming data, and exposes frame-level diagnostics.

**Client opening handshake**

Upgrade a connected `Rest` session to WebSocket and validate the server's response before exchanging frames.

**Text and binary messages**

Send UTF-8 text or exact binary bytes as single-frame or fragmented WebSocket messages.

**Frame-by-frame receiving**

Read frames, inspect opcodes and the FIN state, and accumulate fragments until a complete message is available.

**Ping and Pong**

Use automatic or manual control-frame handling for keep-alive and responsiveness checks.

**Clean close handshake**

Exchange Close frames, inspect the peer's status code and reason, and terminate the underlying connection cleanly.

**Separate read/write paths**

Share a connection between two WebSocket objects when one thread needs to read while another writes.

**Typical connection sequence:** Connect a `Rest` object to the server, call `UseConnection`, call `AddClientHeaders`, send the opening HTTP `GET` request through `Rest`, and then call `ValidateServerHandshake`. Only after validation succeeds should the application call frame send/receive methods.

**Frames versus messages:** A WebSocket message may consist of one frame or several fragments. When receiving a fragmented message, call `ReadFrame` until `FinalFrame` is `True`, then retrieve the accumulated data with `GetFrameData`, `GetFrameDataSb`, or `GetFrameDataBd`.

For an extended overview, see [WebSocket Class Overview](https://www.chilkatsoft.com/websocket_class_overview.asp).

## Object creation, unlocking and error handling

**Create / Free**

```pascal
uses
  Chilkat.WebSocket;

var
  obj: TWebSocket;
begin
  obj := TWebSocket.Create;
  try
    if not obj.IsValid then
      raise Exception.Create('Failed to create a TWebSocket instance.');

    // ... use obj ...

  finally
    obj.Free;
  end;
end;
```

`constructor Create;`

Allocates the underlying CkWebSocket object and returns a new TWebSocket instance. Simply adding **Chilkat.WebSocket** to the unit's `uses` clause is enough to locate and bind to the Chilkat shared library (DLL / .so / .dylib) at runtime — no separate load step is required. Check `obj.IsValid` after calling `Create`; it is `False` if the underlying library could not be found/loaded or the object could not be allocated (for example, when unlicensed).

`destructor Destroy; override;`

Every TWebSocket created by calling `Create` should eventually be released by calling `.Free` (inherited from `TObject`). The destructor automatically disposes the underlying CkWebSocket handle. A native (unmanaged) memory leak occurs if the object is never freed.

Call `Global.UnlockBundle` once at the start of the program, before using this or any other Chilkat class. Any string unlocks a fully functional 30-day trial; a purchased unlock code is used in production. See `guide.md` for the exact code in Lazarus Pascal.

## Members common to every Chilkat class

Documented once per language in `common-members.md`; listed here so this page is self-contained.

| Property | Signature | Access | Meaning |
|---|---|---|---|
| `DebugLogFilePath` | `property DebugLogFilePath: string read GetDebugLogFilePath write SetDebugLogFilePath;` | read/write | If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. |
| `LastErrorHtml` | `property LastErrorHtml: string read GetLastErrorHtml;` | read-only | Provides HTML-formatted information about the last called method or property. |
| `LastErrorText` | `property LastErrorText: string read GetLastErrorText;` | read-only | Provides plain text information about the last called method or property. |
| `LastErrorXml` | `property LastErrorXml: string read GetLastErrorXml;` | read-only | Provides XML-formatted information about the last called method or property. |
| `LastMethodSuccess` | `property LastMethodSuccess: Boolean read GetLastMethodSuccess write SetLastMethodSuccess;` | read/write | Indicates the success or failure of the most recent method call: `True` means success, `False` means failure. |
| `VerboseLogging` | `property VerboseLogging: Boolean read GetVerboseLogging write SetVerboseLogging;` | read/write | If set to `True`, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. |
| `Version` | `property Version: string read GetVersion;` | read-only | Version of the component/library, such as "10.1.0" |

## Member index

| Member | Kind | Signature |
|---|---|---|
| `CloseAutoRespond` | property, read/write | `property CloseAutoRespond: Boolean read GetCloseAutoRespond write SetCloseAutoRespond;` |
| `CloseReason` | property, read-only | `property CloseReason: string read GetCloseReason;` |
| `CloseReceived` | property, read-only | `property CloseReceived: Boolean read GetCloseReceived;` |
| `CloseStatusCode` | property, read-only | `property CloseStatusCode: Integer read GetCloseStatusCode;` |
| `FinalFrame` | property, read-only | `property FinalFrame: Boolean read GetFinalFrame;` |
| `FrameDataLen` | property, read-only | `property FrameDataLen: Integer read GetFrameDataLen;` |
| `FrameOpcode` | property, read-only | `property FrameOpcode: string read GetFrameOpcode;` |
| `FrameOpcodeInt` | property, read-only | `property FrameOpcodeInt: Integer read GetFrameOpcodeInt;` |
| `HeartbeatMs` | property, read/write | `property HeartbeatMs: Integer read GetHeartbeatMs write SetHeartbeatMs;` |
| `IdleTimeoutMs` | property, read/write | `property IdleTimeoutMs: Integer read GetIdleTimeoutMs write SetIdleTimeoutMs;` |
| `IsConnected` | property, read-only | `property IsConnected: Boolean read GetIsConnected;` |
| `NeedSendPong` | property, read-only | `property NeedSendPong: Boolean read GetNeedSendPong;` |
| `PingAutoRespond` | property, read/write | `property PingAutoRespond: Boolean read GetPingAutoRespond write SetPingAutoRespond;` |
| `PongAutoConsume` | property, read/write | `property PongAutoConsume: Boolean read GetPongAutoConsume write SetPongAutoConsume;` |
| `PongConsumed` | property, read-only | `property PongConsumed: Boolean read GetPongConsumed;` |
| `ReadFrameFailReason` | property, read-only | `property ReadFrameFailReason: Integer read GetReadFrameFailReason;` |
| `UncommonOptions` | property, read-only | `property UncommonOptions: string read GetUncommonOptions;` |
| `AddClientHeaders` | method | `function AddClientHeaders: Boolean;` |
| `CloseConnection` | method | `function CloseConnection: Boolean;` |
| `GetFrameData` | method | `function GetFrameData: string;` |
| `GetFrameDataBd` | method | `// binData is a TBinData object. function GetFrameDataBd(binData: TChilkatBase): Boolean;` |
| `GetFrameDataSb` | method | `// sb is a TStringBuilder object. function GetFrameDataSb(sb: TChilkatBase): Boolean;` |
| `LoadTaskCaller` | method | `// task is a TTask object. function LoadTaskCaller(task: TChilkatBase): Boolean;` |
| `PollDataAvailable` | method | `function PollDataAvailable: Boolean;` |
| `ReadFrame` | method | `function ReadFrame: Boolean;` |
| `SendClose` | method | `function SendClose(includeStatus: Boolean;     statusCode: Integer;     const reason: string): Boolean;` |
| `SendFrame` | method | `function SendFrame(const stringToSend: string;     finalFrame: Boolean): Boolean;` |
| `SendFrameBd` | method | `// bdToSend is a TBinData object. function SendFrameBd(bdToSend: TChilkatBase;     finalFrame: Boolean): Boolean;` |
| `SendFrameSb` | method | `// sbToSend is a TStringBuilder object. function SendFrameSb(sbToSend: TChilkatBase;     finalFrame: Boolean): Boolean;` |
| `SendPing` | method | `function SendPing(const pingData: string): Boolean;` |
| `SendPong` | method | `function SendPong: Boolean;` |
| `ShareConnection` | method | `// ws is a TWebSocket object. function ShareConnection(ws: TChilkatBase): Boolean;` |
| `UseConnection` | method | `// connection is a TRest object. function UseConnection(connection: TChilkatBase): Boolean;` |
| `ValidateServerHandshake` | method | `function ValidateServerHandshake: Boolean;` |

## Properties

### WebSocket.CloseAutoRespond

`Chilkat 11.7.0 · pascal · WebSocket · CloseAutoRespond · property · read/write · since 9.5.0.70`

```pascal
property CloseAutoRespond: Boolean read GetCloseAutoRespond write SetCloseAutoRespond;
```

Controls whether Chilkat automatically answers an incoming Close control frame.

- When `True`, an incoming Close is answered automatically if the client did not already initiate the close. After a Close has been both received and sent, Chilkat closes the underlying connection.
- When `False`, the application can detect the received Close through `CloseReceived` or `FrameOpcode` and call `SendClose` itself.

The default is `True`.

**Closing handshake:** A peer that receives a Close and has not already sent one should respond with a Close. Automatic response is usually the safest choice unless the application must control the exact status code or timing.

### WebSocket.CloseReason

`Chilkat 11.7.0 · pascal · WebSocket · CloseReason · property · read-only · since 9.5.0.70`

```pascal
property CloseReason: string read GetCloseReason;
```

Returns the UTF-8 reason text contained in the received Close control frame.

The value is empty when the peer supplied no reason or when no Close frame has been received. A reason is diagnostic text and should not be treated as a stable machine-readable error identifier; use `CloseStatusCode` for protocol-level handling.

### WebSocket.CloseReceived

`Chilkat 11.7.0 · pascal · WebSocket · CloseReceived · property · read-only · since 9.5.0.70`

```pascal
property CloseReceived: Boolean read GetCloseReceived;
```

`True` after a Close control frame has been received on the current WebSocket connection.

When `CloseAutoRespond` is `False`, use this property to determine whether the application needs to call `SendClose` to complete the closing handshake. The received status code and reason, if present, are available through `CloseStatusCode` and `CloseReason`.

### WebSocket.CloseStatusCode

`Chilkat 11.7.0 · pascal · WebSocket · CloseStatusCode · property · read-only · since 9.5.0.70`

```pascal
property CloseStatusCode: Integer read GetCloseStatusCode;
```

Returns the status code contained in the received Close control frame.

Returns `0` when no Close frame has been received or when the received Close frame did not include a status code.

**Meaning of zero:** `0` is an API sentinel; it is not a WebSocket close status transmitted by the peer.

### WebSocket.FinalFrame

`Chilkat 11.7.0 · pascal · WebSocket · FinalFrame · property · read-only · since 9.5.0.70`

```pascal
property FinalFrame: Boolean read GetFinalFrame;
```

`True` if the frame most recently delivered by `ReadFrame` had its WebSocket `FIN` bit set; otherwise `False`.

For a fragmented data message, continue reading while this property is `False`. The fragment with `True` completes the message. Unfragmented messages have `True` on their only frame.

**Control frames:** Close, Ping, and Pong are control frames and are not fragmented by the WebSocket protocol; their `FIN` bit is always set.

### WebSocket.FrameDataLen

`Chilkat 11.7.0 · pascal · WebSocket · FrameDataLen · property · read-only · since 9.5.0.70`

```pascal
property FrameDataLen: Integer read GetFrameDataLen;
```

Returns the number of payload bytes currently accumulated in the internal receive buffer.

The value can represent data from one frame or from multiple calls to `ReadFrame`, which is useful when receiving a fragmented message. The accumulated bytes remain available until retrieved by `GetFrameData`, `GetFrameDataSb`, or `GetFrameDataBd`.

**Message length:** This is the length accumulated so far, not necessarily the final length of the complete WebSocket message. Check `FinalFrame` to determine whether the last received fragment completed the message.

### WebSocket.FrameOpcode

`Chilkat 11.7.0 · pascal · WebSocket · FrameOpcode · property · read-only · since 9.5.0.70`

```pascal
property FrameOpcode: string read GetFrameOpcode;
```

Returns the symbolic opcode of the frame most recently delivered by `ReadFrame`.

| Value | Meaning |
| :--- | :--- |
| `Continuation` | A later fragment of a Text or Binary message |
| `Text` | UTF-8 text data |
| `Binary` | Binary data |
| `Close` | Closing handshake |
| `Ping` | Ping control frame |
| `Pong` | Pong control frame |

Before any frame has been received, the value is the empty string. Ping or Pong frames handled internally by the auto-response/auto-consume options may not be returned as the current frame.

### WebSocket.FrameOpcodeInt

`Chilkat 11.7.0 · pascal · WebSocket · FrameOpcodeInt · property · read-only · since 9.5.0.70`

```pascal
property FrameOpcodeInt: Integer read GetFrameOpcodeInt;
```

Returns the numeric opcode of the frame most recently delivered by `ReadFrame`.

| Value | Frame type |
| :--- | :--- |
| `0` | Continuation |
| `1` | Text |
| `2` | Binary |
| `8` | Close |
| `9` | Ping |
| `10` | Pong |

Use `FrameOpcode` when a readable symbolic value is preferred.

### WebSocket.HeartbeatMs

`Chilkat 11.7.0 · pascal · WebSocket · HeartbeatMs · property · read/write · since 9.5.0.97`

```pascal
property HeartbeatMs: Integer read GetHeartbeatMs write SetHeartbeatMs;
```

**Full documentation for this property (same in every language):** [Event Callback Examples](https://www.chilkatsoft.com/ai-docs/v/11.7.0/articles/event_callback_examples.md)

Specifies the interval, in milliseconds, between `AbortCheck` event callbacks during supported blocking operations.

The default is `0`, which disables periodic `AbortCheck` callbacks. Set a positive value when the application needs an opportunity to cancel a long-running send or receive operation.

**Not a WebSocket heartbeat:** Despite the property name, this setting does not transmit Ping frames and does not monitor peer liveness. Use `SendPing` and Ping/Pong handling for protocol-level heartbeat behavior.

### WebSocket.IdleTimeoutMs

`Chilkat 11.7.0 · pascal · WebSocket · IdleTimeoutMs · property · read/write`

```pascal
property IdleTimeoutMs: Integer read GetIdleTimeoutMs write SetIdleTimeoutMs;
```

Specifies the maximum number of milliseconds an active send or receive operation may remain stalled while waiting for additional network progress.

The default is `30000` milliseconds (30 seconds). This is an **inactivity timeout**, not a total limit on the duration of the operation. An operation may continue longer than this value as long as data continues to be transferred.

**Not a keep-alive interval:** This property does not automatically send WebSocket Ping frames. Use `SendPing` when the application needs protocol-level keep-alive or responsiveness checks.

### WebSocket.IsConnected

`Chilkat 11.7.0 · pascal · WebSocket · IsConnected · property · read-only · since 9.5.0.70`

```pascal
property IsConnected: Boolean read GetIsConnected;
```

`True` when the underlying WebSocket network connection is currently open; otherwise `False`.

**Connection state is not a health check:** A network interruption may not be detected until the next read or write operation. Use normal I/O results—and optionally Ping/Pong—to determine whether a seemingly connected peer is still responsive.

### WebSocket.NeedSendPong

`Chilkat 11.7.0 · pascal · WebSocket · NeedSendPong · property · read-only · since 9.5.0.70`

```pascal
property NeedSendPong: Boolean read GetNeedSendPong;
```

`True` when a Ping frame has been received but no corresponding Pong has yet been sent.

This property is primarily useful when `PingAutoRespond` is `False`. Call `SendPong` as soon as practical; it automatically sends the received Ping payload in the Pong response.

### WebSocket.PingAutoRespond

`Chilkat 11.7.0 · pascal · WebSocket · PingAutoRespond · property · read/write · since 9.5.0.70`

```pascal
property PingAutoRespond: Boolean read GetPingAutoRespond write SetPingAutoRespond;
```

Controls automatic handling of incoming Ping control frames.

- When `True`, Chilkat sends the required Pong automatically and `ReadFrame` consumes the Ping internally, continuing until another frame is available.
- When `False`, the Ping can be returned to the application. Check `NeedSendPong` and call `SendPong` as soon as practical.

The default is `True`.

**Payload echo:** A Pong sent in response to a Ping must carry the same application data. `SendPong` automatically uses the stored payload of the unanswered Ping.

### WebSocket.PongAutoConsume

`Chilkat 11.7.0 · pascal · WebSocket · PongAutoConsume · property · read/write · since 9.5.0.70`

```pascal
property PongAutoConsume: Boolean read GetPongAutoConsume write SetPongAutoConsume;
```

Controls whether incoming Pong control frames are hidden from the application.

- When `True`, `ReadFrame` consumes Pong frames internally and continues reading until a non-Pong frame is available.
- When `False`, an incoming Pong can be returned normally with `FrameOpcode` equal to `Pong`.

The default is `True`. Check `PongConsumed` after `ReadFrame` to learn whether one or more Pong frames were consumed during that call.

### WebSocket.PongConsumed

`Chilkat 11.7.0 · pascal · WebSocket · PongConsumed · property · read-only · since 9.5.0.70`

```pascal
property PongConsumed: Boolean read GetPongConsumed;
```

`True` if the most recent call to `ReadFrame` internally consumed a Pong frame while `PongAutoConsume` was `True`.

The property is reset to `False` at the beginning of each `ReadFrame` call and set to `True` if a Pong is consumed during that call.

**Why unsolicited Pong is possible:** Either endpoint may send a Pong without a preceding Ping, and a response to an earlier Ping may arrive between application data frames. Automatic consumption allows ordinary read loops to ignore these control frames while still detecting that they occurred.

### WebSocket.ReadFrameFailReason

`Chilkat 11.7.0 · pascal · WebSocket · ReadFrameFailReason · property · read-only · since 9.5.0.70`

```pascal
property ReadFrameFailReason: Integer read GetReadFrameFailReason;
```

When `ReadFrame` returns `False`, this property categorizes the reason:

| Value | Meaning |
| :--- | :--- |
| `0` | No failure is recorded |
| `1` | Read inactivity timeout |
| `2` | Aborted by an application callback |
| `3` | Fatal socket error or lost connection |
| `4` | Invalid WebSocket frame bytes were received |
| `99` | Unexpected catch-all failure |

Use this value for programmatic branching and inspect `LastErrorText` for detailed diagnostics.

### WebSocket.UncommonOptions

`Chilkat 11.7.0 · pascal · WebSocket · UncommonOptions · property · read-only · since 9.5.0.80`

```pascal
property UncommonOptions: string read GetUncommonOptions;
```

Contains a comma-separated list of rarely needed compatibility or platform options. The default is the empty string and should normally remain unchanged.

| Keyword | Effect |
| :--- | :--- |
| `ProtectFromVpn` | On Android, attempts to route the connection outside an installed or active VPN. Introduced in v9.5.0.80. |

**Platform-specific behavior:** This option applies only on Android. Leave the property empty on other platforms and unless bypassing the device VPN is an explicit application requirement.

## Methods

### WebSocket.AddClientHeaders

`Chilkat 11.7.0 · pascal · WebSocket · AddClientHeaders · method · since 9.5.0.70`

```pascal
function  AddClientHeaders: Boolean;
```

Adds the standard client opening-handshake headers to the `Rest` object supplied to `UseConnection`:

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

`Sec-WebSocket-Key` contains a newly generated client nonce used by the server to produce `Sec-WebSocket-Accept`.

**Additional handshake headers:** If the server requires headers such as `Origin`, `Authorization`, cookies, or `Sec-WebSocket-Protocol`, add them through the associated `Rest` object before sending the HTTP upgrade request.

Returns True for success, False for failure.

### WebSocket.CloseConnection

`Chilkat 11.7.0 · pascal · WebSocket · CloseConnection · method · since 9.5.0.70`

```pascal
function  CloseConnection: Boolean;
```

Immediately closes the underlying network connection without completing the WebSocket closing handshake.

Use this method when the connection must be abandoned because of a fatal error, timeout, application shutdown, or an unresponsive peer.

**Preferred shutdown:** For a normal shutdown, call `SendClose`, receive the peer's Close frame with `ReadFrame`, and allow the closing handshake to complete. An abrupt transport close does not provide the peer with a WebSocket status code or reason.

Returns True for success, False for failure.

### WebSocket.GetFrameData

`Chilkat 11.7.0 · pascal · WebSocket · GetFrameData · method · since 9.5.0.70`

```pascal
function  GetFrameData: string;
```

Returns the bytes accumulated by successful calls to `ReadFrame` as a string, then clears the internal receive buffer.

This method is intended for WebSocket text-message data. For arbitrary binary payloads, use `GetFrameDataBd` to avoid interpreting binary bytes as text.

**Fragmented messages:** To retrieve an entire fragmented message, continue calling `ReadFrame` until `FinalFrame` is `True`, and then call `GetFrameData` once. Calling this method earlier returns and clears only the data accumulated so far.

Returns True for success, False for failure.

### WebSocket.GetFrameDataBd

`Chilkat 11.7.0 · pascal · WebSocket · GetFrameDataBd · method · since 9.5.0.70`

```pascal
// binData is a TBinData object.

function  GetFrameDataBd(binData: TChilkatBase): Boolean;
```

Appends the bytes accumulated by successful calls to `ReadFrame` to `binData`, then clears the internal receive buffer.

Use this method for binary messages or whenever the exact received bytes must be preserved. Existing data in the destination `BinData` is retained because the received bytes are appended.

**Receive-buffer ownership:** Calling any one of `GetFrameData`, `GetFrameDataSb`, or `GetFrameDataBd` consumes the same internal buffer. Retrieve the data using only the form needed by the application.

Returns True for success, False for failure.

### WebSocket.GetFrameDataSb

`Chilkat 11.7.0 · pascal · WebSocket · GetFrameDataSb · method · since 9.5.0.70`

```pascal
// sb is a TStringBuilder object.

function  GetFrameDataSb(sb: TChilkatBase): Boolean;
```

Appends the text represented by the bytes accumulated by successful calls to `ReadFrame` to `sb`, then clears the internal receive buffer.

Existing text in the destination `StringBuilder` is retained. This method is most appropriate for text-message data; use `GetFrameDataBd` for arbitrary binary payloads.

**Fragmented messages:** The receive buffer can accumulate multiple frames. Read until `FinalFrame` is `True` before calling this method when the application wants the complete message.

Returns True for success, False for failure.

### WebSocket.LoadTaskCaller

`Chilkat 11.7.0 · pascal · WebSocket · LoadTaskCaller · method · since 9.5.0.80`

```pascal
// task is a TTask object.

function  LoadTaskCaller(task: TChilkatBase): Boolean;
```

Loads the caller object associated with an asynchronous `Task` method invocation.

This is used by Chilkat's asynchronous task infrastructure when access to the original `WebSocket` object is required after the task completes.

Returns True for success, False for failure.

### WebSocket.PollDataAvailable

`Chilkat 11.7.0 · pascal · WebSocket · PollDataAvailable · method · since 9.5.0.70`

```pascal
function  PollDataAvailable: Boolean;
```

Checks whether bytes are currently waiting to be read from the underlying WebSocket connection.

Returns `True` when incoming data is available and `False` when no data is presently waiting.

**Polling is only a snapshot:** A `True` result does not mean that an entire WebSocket frame or message has arrived. Call `ReadFrame` to parse the protocol frame. A `False` result does not indicate that the peer will not send data later.

### WebSocket.ReadFrame

`Chilkat 11.7.0 · pascal · WebSocket · ReadFrame · method · since 9.5.0.70`

```pascal
function  ReadFrame: Boolean;
```

Reads the next WebSocket frame from the connected server. On success, the method updates `FrameOpcode`, `FrameOpcodeInt`, `FinalFrame`, and `FrameDataLen`.

Frame payload bytes are added to an internal receive buffer. The buffer may therefore contain data accumulated by multiple calls to `ReadFrame`. Retrieve and clear it with `GetFrameData`, `GetFrameDataSb`, or `GetFrameDataBd`.

**Reading a complete message**

Call `ReadFrame` until `FinalFrame` is `True`, then retrieve the accumulated message data. A fragmented message begins with a Text or Binary frame and continues with one or more Continuation frames.

**Control-frame automation:** Depending on `PingAutoRespond` and `PongAutoConsume`, incoming Ping and Pong frames may be handled internally, causing this method to continue reading until another frame is available. If the method returns `False`, inspect `ReadFrameFailReason` and `LastErrorText`.

Returns True for success, False for failure.

### WebSocket.SendClose

`Chilkat 11.7.0 · pascal · WebSocket · SendClose · method · since 9.5.0.70`

```pascal
function  SendClose(includeStatus: Boolean;
    statusCode: Integer;
    const reason: string): Boolean;
```

Sends a WebSocket Close control frame and begins or completes the closing handshake.

- If `includeStatus` is `False`, the Close frame contains no status code and `statusCode` and `reason` are ignored.
- If `includeStatus` is `True`, the frame contains `statusCode` followed by the UTF-8 bytes of `reason`.

The complete Close payload cannot exceed 125 bytes, leaving at most 123 bytes for the UTF-8 reason after the two-byte status code. Chilkat truncates an overlong reason. The API accepts status-code integers from 0 through 16383.

**Protocol-valid status codes:** The API's numeric range is broader than the set valid for transmission under RFC 6455. Use a defined protocol code such as `1000` for normal closure, or an appropriate application code in the `3000`–`4999` range. Codes `1005`, `1006`, and `1015` are reserved reporting values and must not be sent in a Close frame.

**Clean close:** After initiating a close, read the peer's Close response. If this method answers a Close already received from the server, Chilkat also closes the underlying connection after sending the response.

Returns True for success, False for failure.

### WebSocket.SendFrame

`Chilkat 11.7.0 · pascal · WebSocket · SendFrame · method · since 9.5.0.70`

```pascal
function  SendFrame(const stringToSend: string;
    finalFrame: Boolean): Boolean;
```

Sends one WebSocket **text data frame** containing `stringToSend`. WebSocket text data is UTF-8 on the wire.

- Set `finalFrame` to `True` when this frame completes the message.
- Set `finalFrame` to `False` when additional frames will follow as part of the same fragmented message.

For a normal unfragmented text message, call this method once with `finalFrame` set to `True`. For a fragmented message, call it repeatedly and set `True` only for the final fragment.

**Frames and messages:** A WebSocket message may contain one frame or multiple fragments. Do not begin a second data message until the current fragmented message has been completed. Control frames such as Ping, Pong, and Close may occur between message fragments.

Returns True for success, False for failure.

### WebSocket.SendFrameBd

`Chilkat 11.7.0 · pascal · WebSocket · SendFrameBd · method · since 9.5.0.70`

```pascal
// bdToSend is a TBinData object.

function  SendFrameBd(bdToSend: TChilkatBase;
    finalFrame: Boolean): Boolean;
```

Sends one WebSocket **binary data frame** containing the current bytes in `bdToSend`.

- Set `finalFrame` to `True` when this frame completes the binary message.
- Set `finalFrame` to `False` when additional binary-message fragments will follow.

For an ordinary single-frame binary message, set `finalFrame` to `True`.

**Exact bytes:** No text encoding is involved. The bytes stored in `bdToSend` become the frame payload, while Chilkat applies the client-side WebSocket framing and masking required by the protocol.

Returns True for success, False for failure.

### WebSocket.SendFrameSb

`Chilkat 11.7.0 · pascal · WebSocket · SendFrameSb · method · since 9.5.0.70`

```pascal
// sbToSend is a TStringBuilder object.

function  SendFrameSb(sbToSend: TChilkatBase;
    finalFrame: Boolean): Boolean;
```

Sends one WebSocket **text data frame** containing the current contents of `sbToSend`.

- Set `finalFrame` to `True` when this frame completes the message.
- Set `finalFrame` to `False` when more fragments will follow.

For an ordinary single-frame text message, set `finalFrame` to `True`. WebSocket text data is UTF-8 on the wire.

**Message fragmentation:** Repeated calls with `finalFrame` set to `False` create fragments of the same text message. Complete the message with a final call that passes `True`.

Returns True for success, False for failure.

### WebSocket.SendPing

`Chilkat 11.7.0 · pascal · WebSocket · SendPing · method · since 9.5.0.70`

```pascal
function  SendPing(const pingData: string): Boolean;
```

Sends a WebSocket Ping control frame. If `pingData` is non-empty, its UTF-8 bytes are included as the Ping payload.

WebSocket control-frame payloads are limited to 125 bytes. If the UTF-8 representation exceeds this limit, Chilkat truncates it to 125 bytes.

**Ping/Pong behavior:** A peer that receives a Ping is expected to send a Pong containing the same application data as soon as practical. Ping is useful for protocol-level liveness checks, but receiving a Pong does not by itself prove that the application running above the connection is healthy.

Returns True for success, False for failure.

### WebSocket.SendPong

`Chilkat 11.7.0 · pascal · WebSocket · SendPong · method · since 9.5.0.70`

```pascal
function  SendPong: Boolean;
```

Sends a WebSocket Pong control frame.

When a Ping has been received and has not yet been answered, this method automatically uses the previously received Ping payload as the Pong payload, as required for a Ping response.

**Manual response mode:** This method is normally used when `PingAutoRespond` is `False` and `NeedSendPong` is `True`. When automatic Ping handling is enabled, Chilkat sends the Pong internally.

Returns True for success, False for failure.

### WebSocket.ShareConnection

`Chilkat 11.7.0 · pascal · WebSocket · ShareConnection · method · since 11.0.0`

```pascal
// ws is a TWebSocket object.

function  ShareConnection(ws: TChilkatBase): Boolean;
```

**Full documentation for this method (same in every language):** [C# WebSocket Bidirectional Reading/Writing in Threads](https://www.chilkatsoft.com/ai-docs/v/11.7.0/articles/websocket_csharp_bidirectional.md) · [C++ WebSocket Bidirectional Reading/Writing in Threads](https://www.chilkatsoft.com/ai-docs/v/11.7.0/articles/websocket_cpp_bidirectional.md)

Causes the calling `WebSocket` object to share the already-established WebSocket connection owned by `ws`.

This enables a bidirectional design in which separate `WebSocket` objects operate on the same connection—for example, one thread blocks in `ReadFrame` while another thread sends frames.

**Concurrency model:** Use this feature to separate the read path from the write path. The application remains responsible for coordinating object lifetime, shutdown, and higher-level message state. Avoid multiple concurrent readers or multiple unsynchronized writers unless the application provides its own coordination.

Returns True for success, False for failure.

### WebSocket.UseConnection

`Chilkat 11.7.0 · pascal · WebSocket · UseConnection · method · since 9.5.0.70`

```pascal
// connection is a TRest object.

function  UseConnection(connection: TChilkatBase): Boolean;
```

Associates this `WebSocket` object with an existing, connected `Rest` object and prepares it for a client-side WebSocket session.

The opening WebSocket handshake is an HTTP `GET` upgrade request. Using `Rest` for the underlying connection allows the application to configure TLS, proxies, authentication, custom request headers, IPv6, socket options, bandwidth limits, and other connection features before the upgrade is performed.

**Client-side API:** Chilkat.WebSocket initiates connections to WebSocket servers. It does not listen for incoming connections or implement a WebSocket server endpoint.

**Typical opening sequence**

1. Connect the `Rest` object to the server.
2. Call `UseConnection`.
3. Call `AddClientHeaders`.
4. Send the HTTP `GET` request with the `Rest` object.
5. Call `ValidateServerHandshake`.

Returns True for success, False for failure.

### WebSocket.ValidateServerHandshake

`Chilkat 11.7.0 · pascal · WebSocket · ValidateServerHandshake · method · since 9.5.0.70`

```pascal
function  ValidateServerHandshake: Boolean;
```

Validates the server's response to the WebSocket opening handshake sent through the associated `Rest` object.

Validation checks that the server accepted the HTTP upgrade and returned the expected WebSocket handshake response, including the value derived from the client's `Sec-WebSocket-Key`. If this method returns `True`, the connection has entered the WebSocket protocol and data or control frames may be exchanged.

**Call order:** Call this method only after the `Rest` object has sent the opening `GET` request and received the server's response. A successful HTTP request alone does not establish a WebSocket session; the response must also pass this validation.

Returns True for success, False for failure.

## Events and callbacks

Chilkat for Pascal supports three synchronous event callbacks: `OnAbortCheck`, `OnPercentDone`, and `OnProgressInfo`. Each is a property of the class; assign a method of one of your own objects (an *of object* handler) to receive the callbacks, or assign `nil` to unhook. The handler types are declared in the `Chilkat.Base` unit:

```pascal
TChilkatAbortCheckEvent   = function(Sender: TChilkatBase): Boolean of object;
TChilkatPercentDoneEvent  = function(Sender: TChilkatBase; PctDone: Integer): Boolean of object;
TChilkatProgressInfoEvent = procedure(Sender: TChilkatBase; const Name, Value: string) of object;
```

All Chilkat methods are synchronous, so callbacks are invoked on the thread that called the method -- if the method was called from the main thread, it is safe to access UI elements from the handler. The `HeartbeatMs` property controls the frequency of `OnAbortCheck` callbacks (the default of 0 means no AbortCheck events fire). Returning `True` from an `OnAbortCheck` or `OnPercentDone` handler aborts the running method.

### WebSocket.AbortCheck (event)

`Chilkat 11.7.0 · pascal · WebSocket · AbortCheck · event`

```pascal
// TChilkatAbortCheckEvent = function(Sender: TChilkatBase): Boolean of object;

property OnAbortCheck: TChilkatAbortCheckEvent;
```

Enables a method call to be aborted by triggering the AbortCheck event at intervals defined by the `HeartbeatMs` property. If HeartbeatMs is set to its default value of 0, no events will occur. For instance, set HeartbeatMs to 200 to trigger 5 AbortCheck events per second.

**Event callback implementation:**

```pascal
// A handler is a method of one of your own classes, e.g. a form:
function TMyObject.WebSocketAbortCheck(Sender: TChilkatBase): Boolean;
begin
  // Called every HeartbeatMs milliseconds while a method is running.
  // Return True to abort the method; return False to continue.
  Result := False;
end;
```

**To add an event handler:**

```pascal
websocket := TWebSocket.Create;
websocket.HeartbeatMs := 250;   // fire OnAbortCheck 4 times per second
websocket.OnAbortCheck := MyObject.WebSocketAbortCheck;
```

### WebSocket.PercentDone (event)

`Chilkat 11.7.0 · pascal · WebSocket · PercentDone · event`

```pascal
// TChilkatPercentDoneEvent = function(Sender: TChilkatBase; PctDone: Integer): Boolean of object;

property OnPercentDone: TChilkatPercentDoneEvent;
```

This provides the percentage completion for any method involving network communications or time-consuming processing, assuming the progress can be measured as a percentage. This event is triggered only when it's possible and logical to express the operation's progress as a percentage. The `pctDone` argument will range from 1 to 100. For methods that finish quickly, the number of PercentDone callbacks may vary, but the final callback will have `pctDone` equal to 100. For longer operations, callbacks will not exceed one per percentage point (e.g., 1, 2, 3, ..., 98, 99, 100).

The PercentDone callback also acts as an `AbortCheck` event. For fast methods where PercentDone fires, an AbortCheck event may not trigger since the PercentDone callback already provides an opportunity to abort. For longer operations, where time between PercentDone callbacks is extended, AbortCheck callbacks enable more responsive operation termination.

To abort the operation, set the `abort` output argument to `True`. This will cause the method to terminate and return a failure status or corresponding failure value.

**Event callback implementation:**

```pascal
// A handler is a method of one of your own classes, e.g. a form:
function TMyObject.WebSocketPercentDone(Sender: TChilkatBase; PctDone: Integer): Boolean;
begin
  // PctDone ranges from 1 to 100.
  WriteLn('Percent done: ', PctDone);
  // Return True to abort the method; return False to continue.
  Result := False;
end;
```

**To add an event handler:**

```pascal
websocket := TWebSocket.Create;
websocket.OnPercentDone := MyObject.WebSocketPercentDone;
```

### WebSocket.ProgressInfo (event)

`Chilkat 11.7.0 · pascal · WebSocket · ProgressInfo · event`

```pascal
// TChilkatProgressInfoEvent = procedure(Sender: TChilkatBase; const Name, Value: string) of object;

property OnProgressInfo: TChilkatProgressInfoEvent;
```

This event callback provides `tag name`/value pairs that detail what occurs during a method call. To discover existing tag names, create code to handle the event, emit the pairs, and review them. Most tag names are self-explanatory.

Note: Some Chilkat methods don't fire any ProgressInfo events.

**Event callback implementation:**

```pascal
// A handler is a method of one of your own classes, e.g. a form:
procedure TMyObject.WebSocketProgressInfo(Sender: TChilkatBase; const Name, Value: string);
begin
  WriteLn(Name, ': ', Value);
end;
```

**To add an event handler:**

```pascal
websocket := TWebSocket.Create;
websocket.OnProgressInfo := MyObject.WebSocketProgressInfo;
```

## Related classes

[`BinData`](https://www.chilkatsoft.com/ai-docs/v/11.7.0/pascal/classes/BinData.md), [`Rest`](https://www.chilkatsoft.com/ai-docs/v/11.7.0/pascal/classes/Rest.md), [`StringBuilder`](https://www.chilkatsoft.com/ai-docs/v/11.7.0/pascal/classes/StringBuilder.md)

