Chilkat.WebSocket Class Overview

Chilkat.WebSocket provides WebSocket client functionality over a Chilkat Rest connection. It handles the WebSocket opening handshake, sending and receiving text or binary frames, ping/pong control frames, clean close handshakes, polling for available data, shared connections for multi-threaded read/write patterns, and detailed frame-status diagnostics.

What the Class Is Used For

Use Chilkat.WebSocket when an application needs to communicate with a WebSocket server after establishing the underlying connection with Chilkat.Rest. The WebSocket handshake begins as an HTTP GET request, so the Rest object provides the connection, TLS, proxy, authentication, custom-header, socket, IPv6, SSH tunnel, and bandwidth-throttling features used during the opening handshake.

Open a WebSocket Session Use UseConnection, AddClientHeaders, a REST request, and ValidateServerHandshake.
Send Text or Binary Frames Send string, StringBuilder, or BinData frames with final-frame control.
Read Incoming Frames Use ReadFrame, then inspect opcode, final-frame status, data length, and retrieve accumulated frame data.
Handle Control Frames Automatically or manually handle Close, Ping, and Pong frames.

Typical WebSocket Workflow

  1. Create and connect a Rest object to the WebSocket server.
  2. Create a WebSocket object.
  3. Call UseConnection to initialize the WebSocket object with the Rest connection.
  4. Call AddClientHeaders to add the required WebSocket opening handshake headers to the Rest request.
  5. Use the Rest object to send the opening HTTP GET handshake.
  6. Call ValidateServerHandshake. If successful, the WebSocket session is open.
  7. Send application data with SendFrame, SendFrameSb, or SendFrameBd.
  8. Read incoming frames with ReadFrame, then retrieve frame data with GetFrameData, GetFrameDataSb, or GetFrameDataBd.
  9. Close cleanly with SendClose, or forcibly with CloseConnection when necessary.
Key setup rule: Every WebSocket session begins with UseConnection. The WebSocket object depends on the previously established Rest connection.

Opening Handshake

Step Member Purpose
Attach the connection UseConnection Initializes the WebSocket session using an existing Rest connection.
Add required WebSocket headers AddClientHeaders Adds client-side opening handshake headers: Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Key, and Sec-WebSocket-Version: 13.
Send the HTTP GET handshake Rest method call The opening handshake is sent by the associated Rest object, allowing custom headers, authentication, proxy settings, TLS, and other transport features.
Validate the server response ValidateServerHandshake Confirms that the server accepted the WebSocket opening handshake. After a successful validation, the application may send and receive frames.

Core Concepts

Concept Meaning Important Members
REST-Based Connection The WebSocket object uses a Rest object because the WebSocket opening handshake starts as an HTTP GET request. UseConnection, AddClientHeaders, ValidateServerHandshake
Data Frame A WebSocket frame carrying text, binary, or continuation data. SendFrame, SendFrameBd, ReadFrame
Control Frame A protocol-level frame such as Close, Ping, or Pong. SendClose, SendPing, SendPong
Final Frame Indicates whether the last received data frame completed the message. FinalFrame
Accumulated Frame Data Data accumulated from one or more calls to ReadFrame, retrieved and cleared by GetFrameData* methods. FrameDataLen, GetFrameData, GetFrameDataSb, GetFrameDataBd
Clean Close The WebSocket protocol expects a Close frame to be sent and a Close response to be received before the underlying connection is closed. SendClose, CloseAutoRespond, CloseReceived

Connection and Timeout Properties

Property Purpose Guidance
IsConnected Indicates whether the WebSocket is connected. Check before attempting further reads or writes when connection state is in doubt.
IdleTimeoutMs Maximum time to wait when receiving or sending has halted. Default is 30000 milliseconds. This is an idle timeout, not an overall maximum operation timeout.
HeartbeatMs Interval between AbortCheck event callbacks. Default is 0, meaning no AbortCheck callbacks.
LastErrorText Diagnostic text for the last method or property access. Check after failures or unexpected behavior. Diagnostic information may be available regardless of success or failure.
UncommonOptions Catch-all property for uncommon needs. Normally empty. Documented keyword: ProtectFromVpn, which on Android bypasses any VPN that may be installed or active.

Reading Frames

Member Purpose Important Details
ReadFrame Reads a single frame from the connected WebSocket. On success, updates FrameOpcode, FrameDataLen, and FinalFrame.
FrameOpcode Text name of the last frame type received. Possible values: Continuation, Text, Binary, Close, Ping, or Pong.
FrameOpcodeInt Numeric opcode of the last frame type received. 0 Continuation, 1 Text, 2 Binary, 8 Close, 9 Ping, 10 Pong.
FinalFrame Indicates whether the last data frame read was final. Use when handling fragmented messages.
FrameDataLen Number of bytes accumulated from received frame data. Retrieve accumulated data with one of the GetFrameData* methods.
ReadFrameFailReason Provides a numeric reason when ReadFrame returns false. Use to distinguish timeout, abort, lost connection, invalid frame bytes, or unknown failures.

ReadFrame Failure Reasons

Value Meaning Typical Response
0 No failure. No action needed.
1 Read timeout. Decide whether to retry, poll again, send a ping, or close the connection.
2 Aborted by application callback. Treat as an application-requested cancellation.
3 Fatal socket error; lost connection. Treat the connection as broken and reconnect if appropriate.
4 Invalid WebSocket frame bytes received. Treat as a protocol/data error.
99 Unknown failure. Check LastErrorText; this should not normally occur.

Retrieving Received Frame Data

Method Returns / Target Behavior
GetFrameData String Returns accumulated received frame data as a string. Calling this method clears the internal receive buffer.
GetFrameDataSb StringBuilder Appends accumulated received frame data to the supplied StringBuilder, then clears the internal receive buffer.
GetFrameDataBd BinData Appends accumulated received frame data to the supplied BinData, then clears the internal receive buffer.
Buffer rule: Each GetFrameData* method clears the WebSocket internal receive buffer after retrieving the accumulated data.

Sending Data Frames

Method Data Source Final Frame Argument
SendFrame String Set finalFrame to true if this is the final frame in the message; otherwise false.
SendFrameSb StringBuilder Uses the contents of the supplied StringBuilder.
SendFrameBd BinData Uses the contents of the supplied BinData for binary frame data.
Fragmentation rule: For a one-frame message, pass finalFrame = true. Use false only when intentionally sending a fragmented message that will be completed by a later final frame.

Ping and Pong Handling

Member Default / Behavior Guidance
PingAutoRespond Default is true. Incoming Ping frames are automatically answered with Pong frames. When true, ReadFrame auto-consumes Ping frames and continues reading the next incoming frame.
NeedSendPong True when a Ping frame was received and no Pong has yet been sent. Used when PingAutoRespond is false and the application is responsible for calling SendPong.
SendPing Sends a Ping control frame, optionally with text data. If ping data is non-empty, its UTF-8 representation must be 125 bytes or less. Chilkat truncates it if necessary.
SendPong Sends a Pong control frame. If replying to a received Ping, the previously received Ping data is automatically sent in the Pong frame.
PongAutoConsume Default is true. Incoming Pong frames are automatically consumed. This prevents unexpected Pong frames from disrupting application-level frame reads.
PongConsumed True if the last ReadFrame call auto-consumed a Pong frame. Reset to false each time ReadFrame is called.

Close Handling

Member Purpose Important Details
CloseAutoRespond Controls whether a Close frame is automatically sent in response to a received Close frame. Default is true. When both Close frames have been received and sent, the underlying connection is automatically closed.
CloseReceived Indicates whether a Close frame has already been received. Useful when CloseAutoRespond is false and the application must decide whether to send a Close response.
CloseStatusCode Status code received with the Close frame. Returns 0 if no status code was provided or no Close frame has been received.
CloseReason Reason string received with the Close frame, if any. Inspect when the peer explains why it is closing the connection.
SendClose Sends a Close control frame. For normal closure, status code 1000 is used. The reason must be 123 UTF-8 bytes or less; Chilkat truncates if necessary.
CloseConnection Forcibly closes the underlying connection. This is a non-clean close. Prefer SendClose and receiving the Close response when possible.
Status-code limits: When using SendClose, the status code must be in the range 0 to 16383.

Polling, Async, and Shared Connections

Method Purpose When to Use
PollDataAvailable Checks whether data is waiting to be read. Use before calling ReadFrame when the application wants to avoid waiting when no data is available.
LoadTaskCaller Loads the caller of an async method’s task. Used with asynchronous task workflows.
ShareConnection Shares another WebSocket object’s existing connection. Enables multi-threaded applications to read and write to the WebSocket simultaneously.

Method Summary by Category

Category Methods Purpose
Handshake setup UseConnection, AddClientHeaders, ValidateServerHandshake Initialize the WebSocket over a REST connection, add required opening headers, and validate the server’s handshake response.
Read frames ReadFrame, PollDataAvailable Read incoming frames or check whether incoming data is waiting.
Retrieve received data GetFrameData, GetFrameDataSb, GetFrameDataBd Retrieve accumulated frame data as a string, StringBuilder content, or BinData content.
Send data frames SendFrame, SendFrameSb, SendFrameBd Send text or binary WebSocket frames.
Control frames SendPing, SendPong, SendClose Send Ping, Pong, and Close control frames.
Connection close SendClose, CloseConnection Close cleanly using the WebSocket protocol or forcibly close the underlying connection.
Threading and async ShareConnection, LoadTaskCaller Support simultaneous read/write patterns or async task workflows.

Diagnostics and Troubleshooting

Problem Area Member What to Check
Handshake fails UseConnection, AddClientHeaders, ValidateServerHandshake Confirm the REST connection is established, required headers were added, the opening GET was sent correctly, and the server accepted the handshake.
ReadFrame returns false ReadFrameFailReason, LastErrorText Check whether the failure was a timeout, application abort, lost connection, invalid frame bytes, or an unknown error.
Unexpected Ping frames PingAutoRespond Leave PingAutoRespond enabled to automatically answer and consume Ping frames.
Unexpected Pong frames PongAutoConsume, PongConsumed Leave PongAutoConsume enabled so application reads are not disrupted by unexpected Pong frames.
Need to reply manually to Ping PingAutoRespond, NeedSendPong, SendPong If auto response is disabled, check NeedSendPong and call SendPong as soon as possible.
Connection closes unexpectedly CloseReceived, CloseStatusCode, CloseReason Check whether a Close frame was received and inspect any status code or reason sent by the peer.
Frame data appears missing after retrieval GetFrameData, GetFrameDataSb, GetFrameDataBd Remember that retrieving frame data clears the internal receive buffer.
Need operation details after failure LastErrorText Check diagnostic text after failed or unexpected handshake, read, write, ping/pong, close, or connection operations.

Common Pitfalls

Pitfall Better Approach
Trying to use WebSocket without first attaching a REST connection. Establish the Rest connection, then call UseConnection.
Forgetting to add client handshake headers. Call AddClientHeaders before sending the opening WebSocket GET request.
Sending or receiving frames before validating the server handshake. Call ValidateServerHandshake after the opening handshake response is received.
Assuming IdleTimeoutMs is an overall operation timeout. Treat it as the maximum wait when sending or receiving has halted.
Ignoring Ping and Pong protocol behavior. Leave PingAutoRespond and PongAutoConsume enabled unless manual control is required.
Using CloseConnection for normal shutdown. Use SendClose and receive the Close response for a clean WebSocket close.
Retrieving frame data multiple times expecting the same data. Store the result when calling GetFrameData* because the internal receive buffer is cleared.

Best Practices

Recommendation Reason
Configure the Rest object fully before the WebSocket handshake. The REST object provides the underlying connection, TLS, proxy, authentication, custom headers, socket options, and related transport behavior.
Keep automatic Ping and Pong handling enabled unless there is a specific reason not to. It prevents control frames from interrupting application-level frame reads.
Use PollDataAvailable when non-blocking-style behavior is desired. It lets the application check whether a frame is waiting before attempting a read.
Use ReadFrameFailReason whenever ReadFrame fails. It quickly identifies timeout, abort, socket loss, invalid frame data, or unknown failures.
Use BinData methods for binary messages. SendFrameBd and GetFrameDataBd avoid text conversion issues.
Use SendClose for normal shutdown. It follows the WebSocket protocol’s clean close behavior.
Check LastErrorText after failures. It provides useful diagnostic detail for connection setup, handshake validation, frame reads, frame writes, ping/pong handling, and close handling.

Summary

Chilkat.WebSocket is the Chilkat class for WebSocket client sessions over a Rest connection. It uses the REST object for the opening HTTP GET handshake and transport-level features, then provides WebSocket-specific methods for sending and reading frames, retrieving frame data, handling Ping/Pong and Close control frames, polling for data, sharing connections, and diagnosing read failures.

The most important practical guidance is to set up the Rest connection first, call UseConnection, add and send the client handshake, validate the server handshake, leave automatic Ping/Pong handling enabled unless manual handling is required, and use SendClose for a clean shutdown.