int WebSocketClient::send()

in AZ3166/src/libraries/WebSocket/src/WebSocketClient.cpp [195:270]


int WebSocketClient::send(const char *str, long size, WS_Message_Type messageType, bool isFinal)
{
    if (_tcpSocket == NULL)
    {
        ERROR("unable to send data when WebSocket is disconnected.");
        return NSAPI_ERROR_NO_SOCKET;
    }

    if (str == NULL || size <= 0)
    {
        return 0;
    }

    char msg[15];

    char opcode = 0x00;
    if (messageType == WS_Message_Ping) 
    {
        opcode = WS_OPCODE_PING | WS_FINAL_BIT;
    }
    else if (messageType == WS_Message_Pong)
    {
        opcode = WS_OPCODE_PONG | WS_FINAL_BIT;
    }
    else if (messageType == WS_Message_Close)
    {
        opcode = WS_OPCODE_CLOSE | WS_FINAL_BIT;
    }
    else
    {
        if (_firstFrame)
        {
            _messageType = messageType;
            if (messageType == WS_Message_Text)
            {
                opcode = WS_OPCODE_TEXT;
            }
            else if (messageType == WS_Message_Binary)
            {
                opcode = WS_OPCODE_BINARY;
            }
        }
        else
        {
            opcode = WS_OPCODE_CONT;
        }

        if (isFinal)
        {
            opcode |= WS_FINAL_BIT;

            // Reset the states of next message to send
            _firstFrame = true;
        }
        else
        {
            // Next frame will be a continuation frame
            _firstFrame = false;
        }
    }

    msg[0] = opcode;

    int idx = 1;
    idx += sendLength(size, msg + idx);
    idx += sendMask(msg + idx);
    int res = write(msg, idx);
    if (res != idx)
    {
        ERROR("Send websocket frame header failed.");
        return -1;
    }

    res = write(str, size);
    return res == -1 ? -1 : res + idx;
}