/** * This method should be used when you want to send a message without having to bother * with framing yourself. Just give the data type and the data and this function will * handle the rest. * If you want to do framing yourself, use sendFrame() instead. * * @param int $nType The message type * @param array|string The data or text that would form the payload-data */ public function send($nType, $aData = null) { /* Only send messages when the connection is in the OPEN or CLOSING state */ if ($this->m_nReadyState != static::STATE_OPEN && $this->m_nReadyState != static::STATE_CLOSING) { return false; } /* If the message type is text, the data is a string that must be transformed into a * byte array. */ if ($nType == WebSocketFrame::TYPE_TEXT) { /* If there is data, split per character */ if (strlen($aData) > 0) { $aData = str_split($aData); /* And transform each character into the corresponding byte */ array_walk($aData, function (&$char) { $char = ord($char); }); } else { /* Or use an empty array */ $aData = array(); } } /* Determine how many frames will be needing to send this message */ $nFramesNeeded = (int) (count($aData) / WebSocketFrame::getMaxLength()) + 1; /* Send the date frame by frame */ for ($i = 0; $i < $nFramesNeeded; $i++) { /* The first parameter is the message type. The actual message type must only be set * for the first frame, all following frames must have the continuation frame-type set * The second parameter is true if this is the final frame. False otherwise * The final parameter indicates whether the data should be masked. The protocol only states * that data send from the client MUST be masked. Data that is send by the server shouldn't be * masked. (Point 4.3) * */ $pFrame = new WebSocketFrame($i != 0 ? 0 : $nType, $nFramesNeeded == $i + 1 ? true : false, true); /* Get the piece of the message that should be send in the current frame. */ if (count($aData) > 0) { $pFrame->setData(array_slice($aData, WebSocketFrame::getMaxLength() * $i, WebSocketFrame::getMaxLength())); } /* And use the sendFrame method to actually send the frame to the client. */ if (!$this->sendFrame($pFrame)) { $this->close(false); return false; } } }