webSocketWrite()

Writes data to the given WebSocket.

Synopsis

int webSocketWrite(int socket, string|blob data)

Parameters

Parameter Description
socket The number of the WebSocket the data is written to.
data The data which is written to the WebSocket.

Return value

On success the function returns the number of bytes written and -1 on error.

Errors

Errors can be an illegal number of arguments or a wrong socket number.

Description

The function writes data onto the given WebSocket. For this process consider the following:

  • Especially on Linux and with SSL enabled, it is possible that the send buffer overflows when too much data is written to the WebSocket without interruption. The limit when this happens is depending on OS defaults and configuration.
  • It is therefore recommended to implement some kind of confirmation or handshake between client and server.
  • If this is not possible, it is important that sending from the client is interrupted (e. g. with delay()) before the buffer overflows.
  • To support this, the websocket will automatically be flushed if more than 64kB are buffered for it. If this fails, webSocketWrite() will return an error (-1). After such an error, getLastError() will contain an error with code ErrCode::UNEXPECTEDSTATE. Example code for handling this error:
    int writeToWebSocket(int socket, string data)
    {
      for (int i = 1; i <= 5; i++)
      {
        int written = webSocketWrite(socket, data);
        if ( written >= 0 )
          return written;  // success
    
        dyn_errClass err = getLastError();
        if ( getErrorCode(err) != (int)ErrCode::UNEXPECTEDSTATE )
          return written;  // error different from send buffer full
    
        // send buffer is full, use delay to allow socket to process data,
        // then try again
        delay(0, 10);
      }
    
      return -1;
    }

Assignment

WebSocket functions

Availability

CTRL