Data received over websocket.

        First received data will allways be handshake accepting connection.
        We need to check how big the header is so we can send event data
        as a proper json object.
353602
def data_received(self, data):
        
        if self.state == STATE_STARTING:
            self.state = STATE_RUNNING
            _LOGGER.debug('Websocket handshake: %s', data.decode())
            return
        _LOGGER.debug('Websocket data: %s', data)

        while len(data) > 0:
            payload, extra_data = self.get_payload(data)
            self._data = payload ###
            self.async_session_handler_callback('data')###
            #self.async_callback(payload)
            data = extra_data
509239
function event_receive($client_socket, $events, $client_id)
    {
        $data = Stream::read($client_socket, $this->buffer_size);
        if($data !== false)
        {
            $this->protocol->onReceive($this, $client_id, 0, $data);
        }
        else
        {
            $this->close($client_id);
        }
    }
310961
def receive(max_len=nil)
      max_len ||= 1024

      begin
        data = @socket.recv(max_len)
      rescue IO::WaitReadable
        @logger.logv 'Retrying receive...'
        IO.select([@socket])
        retry
      rescue Exception => e
        if e.class != 'IOError' && e.message != 'closed stream'
          @logger.log_exception(e, 'EXCEPTION during receive!')
        end
      end

      if (data.nil? || data.empty?)
        @logger.log "Client #{@socket.inspect} disconnected!"
        data = ''
      else
        @logger.log "Received #{data.length} bytes"
      end

      return data
    end
1181739
function Communication() {
		// setup abstract layer
		core.CommunicationAbstract.apply(this, arguments);

		// when socket is closed we will emit the close event
		this.object.on('close', this.emit.bind(this, 'close'));

		// setup a json stream handler there rescive data from the TCP socket
		// remember that this.object is the TCP socket
		jsonStream(this, this.object);
	}
221849
def net_recv(ws, conn):
    '''  '''
    in_data = conn.recv(RECEIVE_BYTES)
    if not in_data:
        # A receive of zero bytes indicates the TCP socket has been closed. We
        # need to pass None to wsproto to update its internal state.
        print('Received 0 bytes (connection closed)')
        ws.receive_data(None)
    else:
        print('Received {} bytes'.format(len(in_data)))
        ws.receive_data(in_data)
170921
function() {
        try {
          if (socket && socket.readyState == 1) {
            return;
          }

          socket = new WebSocket(address, []);

          socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
          socketRealTimeStatusInterval = setInterval(function() {
            switch (socket.readyState) {
              case 2:
                onCloseHandler(null);
                break;
              case 3:
                socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
                break;
            }
          }, 5000);

          socket.onopen = function(event) {
            waitForSocketToConnect(function() {
              eventCallback["open"]();
            });
          }

          socket.onmessage = function(event) {
            var messageData = JSON.parse(event.data);
            eventCallback["message"](messageData);

            /**
             * To avoid manually closing socket's connection
             */
            forceCloseSocket = false;

            socketCloseTimeout && clearTimeout(socketCloseTimeout);
            forceCloseTimeout && clearTimeout(forceCloseTimeout);

            socketCloseTimeout = setTimeout(function() {
              /**
               * If message's type is not 5, socket won't get any acknowledge packet,therefore
               * you may think that connection has been closed and you would force socket
               * to close, but before that you should make sure that connection is actually closed!
               * for that, you must send a ping message and if that message don't get any
               * responses too, you are allowed to manually kill socket connection.
               */
              ping();

              /**
               * We set forceCloseSocket as true so that if your ping's response don't make it
               * you close your socket
               */
              forceCloseSocket = true;

              /**
               * If type of messages are not 5, you won't get ant ACK packets
               * for that being said, we send a ping message to be sure of
               * socket connection's state. The ping message should have an
               * ACK, if not, you're allowed to close your socket after
               * 4 * [connectionCheckTimeout] seconds
               */
              forceCloseTimeout = setTimeout(function() {
                if (forceCloseSocket) {
                  socket.close();
                }
              }, connectionCheckTimeout);

            }, connectionCheckTimeout * 1.5);
          }

          socket.onclose = function(event) {
            onCloseHandler(event);
          }

          socket.onerror = function(event) {
            eventCallback["error"](event);
          }
        } catch (error) {
          eventCallback["customError"]({
            errorCode: 4000,
            errorMessage: "ERROR in WEBSOCKET!",
            errorEvent: error
          });
        }
      }
380885
def send(self, data, opcode=ABNF.OPCODE_TEXT):
        

        if not self.sock or self.sock.send(data, opcode) == 0:
            raise WebSocketConnectionClosedException(
                "Connection is already closed.")
1077887
async def _websocket_handler(self, ws):
        """"""
        if self.connected:
            # the socket was already connected, so this is an upgrade
            self.upgrading = True  # hold packet sends during the upgrade

            try:
                pkt = await ws.wait()
            except IOError:  # pragma: no cover
                return
            decoded_pkt = packet.Packet(encoded_packet=pkt)
            if decoded_pkt.packet_type != packet.PING or \
                    decoded_pkt.data != 'probe':
                self.server.logger.info(
                    '%s: Failed websocket upgrade, no PING packet', self.sid)
                return
            await ws.send(packet.Packet(
                packet.PONG,
                data=six.text_type('probe')).encode(always_bytes=False))
            await self.queue.put(packet.Packet(packet.NOOP))  # end poll

            try:
                pkt = await ws.wait()
            except IOError:  # pragma: no cover
                return
            decoded_pkt = packet.Packet(encoded_packet=pkt)
            if decoded_pkt.packet_type != packet.UPGRADE:
                self.upgraded = False
                self.server.logger.info(
                    ('%s: Failed websocket upgrade, expected UPGRADE packet, '
                     'received %s instead.'),
                    self.sid, pkt)
                return
            self.upgraded = True

            # flush any packets that were sent during the upgrade
            for pkt in self.packet_backlog:
                await self.queue.put(pkt)
            self.packet_backlog = []
            self.upgrading = False
        else:
            self.connected = True
            self.upgraded = True

        # start separate writer thread
        async def writer():
            while True:
                packets = None
                try:
                    packets = await self.poll()
                except exceptions.QueueEmpty:
                    break
                if not packets:
                    # empty packet list returned -> connection closed
                    break
                try:
                    for pkt in packets:
                        await ws.send(pkt.encode(always_bytes=False))
                except:
                    break
        writer_task = asyncio.ensure_future(writer())

        self.server.logger.info(
            '%s: Upgrade to websocket successful', self.sid)

        while True:
            p = None
            wait_task = asyncio.ensure_future(ws.wait())
            try:
                p = await asyncio.wait_for(wait_task, self.server.ping_timeout)
            except asyncio.CancelledError:  # pragma: no cover
                # there is a bug (https://bugs.python.org/issue30508) in
                # asyncio that causes a "Task exception never retrieved" error
                # to appear when wait_task raises an exception before it gets
                # cancelled. Calling wait_task.exception() prevents the error
                # from being issued in Python 3.6, but causes other errors in
                # other versions, so we run it with all errors suppressed and
                # hope for the best.
                try:
                    wait_task.exception()
                except:
                    pass
                break
            except:
                break
            if p is None:
                # connection closed by client
                break
            if isinstance(p, six.text_type):  # pragma: no cover
                p = p.encode('utf-8')
            pkt = packet.Packet(encoded_packet=p)
            try:
                await self.receive(pkt)
            except exceptions.UnknownPacketError:  # pragma: no cover
                pass
            except exceptions.SocketIsClosedError:  # pragma: no cover
                self.server.logger.info('Receive error -- socket is closed')
                break
            except:  # pragma: no cover
                # if we get an unexpected exception we log the error and exit
                # the connection properly
                self.server.logger.exception('Unknown receive error')

        await self.queue.put(None)  # unlock the writer task so it can exit
        await asyncio.wait_for(writer_task, timeout=None)
        await self.close(wait=False, abort=True)
578322
function() {
        if(!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            if(this.debug >= 1)
                this.log('[warning] spectate() was called when connection was not established, packet will be dropped');
            return false;
        }

        var buf = new Buffer([1]);
        this.send(buf);

        return true;
    }
234663
def recv(self):
        """"""
        try:
            message = self.ws.recv()
            return json.loads(message)
        except websocket._exceptions.WebSocketConnectionClosedException as ex:
            raise SelenolWebSocketClosedException() from ex
202138
@Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        String clientip = httpRequest.getClientIp();
        log.debugf("receive {}'s websocket handshake packet \r\n{}", clientip, httpRequest.toString());

        TioWebsocketMethodMapper handshake = methods.getHandshake();
        if (handshake != null) {
            handshake.getMethod().invoke(handshake.getInstance(), httpRequest, httpResponse, channelContext);
        }
        return httpResponse;
    }
1181096
def receive_data(self):  # pragma: no cover; no covered since qt event loop
        ''' 
        '''
        while(not self._stop_readout.wait(0.01)):  # use wait(), do not block
            if self._send_data:
                if self.socket_type != zmq.DEALER:
                    raise RuntimeError('You send data without a bidirectional '
                                       'connection! Define a bidirectional '
                                       'connection.')
                self.receiver.send(self._send_data)
                self._send_data = None
            try:
                data_serialized = self.receiver.recv(flags=zmq.NOBLOCK)
                data = self.deserializer(data_serialized)
                self.data.emit(data)
            except zmq.Again:
                pass
        self.finished.emit()
1167318
@Override
	public void processMessage(final WebSocketMessage webSocketData) {

		setDoTransactionNotifications(true);

		final SecurityContext securityContext = getWebSocket().getSecurityContext();
		final App app = StructrApp.getInstance(securityContext);

		try {

			final PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, webSocketData.getNodeData());
			Class type                   = SchemaHelper.getEntityClassForRawType(properties.get(AbstractNode.type));
			final NodeInterface newNode  = app.create(type, properties);

			TransactionCommand.registerNodeCallback(newNode, callback);

			// check for File node and store in WebSocket to receive chunks
			if (newNode instanceof File) {

				getWebSocket().createFileUploadHandler((File) newNode);

			}


		} catch (FrameworkException fex) {

			logger.warn("Could not create node.", fex);
			getWebSocket().send(MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(), true);

		}
	}
286603
def on_message(self, data):
        
        # Trying to parse response
        data = json.loads(data)
        if not data["name"] is None:
            logging.debug("%s: receiving message %s" % (data["name"], data["data"]))
            fct = getattr(self, "on_" + data["name"])
            try:
                res = fct(Struct(data["data"]))
            except:
                # We try without Struct item (on transaction request this can happend)
                res = fct(data["data"])
            if res is not None:
                self.write_message(res)
        else:
            logging.error("SockJSDefaultHandler: data.name was null")
1256760
@Override
    public ByteBuffer read(ByteBuffer receiveBuffer) throws IOException {
        if (!doHandshake(receiveBuffer))
            return null;

        if (!initialHSComplete)
            throw new IllegalStateException("The initial handshake is not complete.");

        if (log.isDebugEnabled()) {
            log.debug("session {} read data status -> {}, initialHSComplete -> {}", session.getSessionId(),
                    session.isOpen(), initialHSComplete);
        }

        merge(receiveBuffer);
        if (!receivedPacketBuf.hasRemaining()) {
            return null;
        }

        needIO:
        while (true) {
            SSLEngineResult result = unwrap();

            if (log.isDebugEnabled()) {
                log.debug("Session {} read data result -> {}, receivedPacketBuf -> {}, appBufSize -> {}",
                        session.getSessionId(), result.toString().replace('\n', ' '),
                        receivedPacketBuf.remaining(), receivedAppBuf.remaining());
            }

            switch (result.getStatus()) {
                case BUFFER_OVERFLOW: {
                    resizeAppBuffer();
                    // retry the operation.
                }
                break;
                case BUFFER_UNDERFLOW: {
                    int packetBufferSize = sslEngine.getSession().getPacketBufferSize();
                    if (receivedPacketBuf.remaining() >= packetBufferSize) {
                        break; // retry the operation.
                    } else {
                        break needIO;
                    }
                }
                case OK: {
                    if (result.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_TASK) {
                        doTasks();
                    }
                    if (receivedPacketBuf.hasRemaining()) {
                        break; // retry the operation.
                    } else {
                        break needIO;
                    }
                }

                case CLOSED: {
                    log.info("Session {} read data failure. SSLEngine will close inbound", session.getSessionId());
                    closeInbound();
                }
                break needIO;

                default:
                    throw new SecureNetException(StringUtils.replace("Session {} SSLEngine read data exception. status -> {}",
                            session.getSessionId(), result.getStatus()));
            }
        }

        return getReceivedAppBuf();
    }
811134
def receive_message(
        sock, operation, request_id, max_message_size=MAX_MESSAGE_SIZE):
    """"""
    header = _receive_data_on_socket(sock, 16)
    length = _UNPACK_INT(header[:4])[0]

    actual_op = _UNPACK_INT(header[12:])[0]
    if operation != actual_op:
        raise ProtocolError("Got opcode %r but expected "
                            "%r" % (actual_op, operation))
    # No request_id for exhaust cursor "getMore".
    if request_id is not None:
        response_id = _UNPACK_INT(header[8:12])[0]
        if request_id != response_id:
            raise ProtocolError("Got response id %r but expected "
                                "%r" % (response_id, request_id))
    if length <= 16:
        raise ProtocolError("Message length (%r) not longer than standard "
                            "message header size (16)" % (length,))
    if length > max_message_size:
        raise ProtocolError("Message length (%r) is larger than server max "
                            "message size (%r)" % (length, max_message_size))

    return _receive_data_on_socket(sock, length - 16)
575522
def send(self, data):
        
        self.logger.debug('Send data: {}'.format(data))

        if not self.connected:
            self.logger.warning('Connection not established. Return...')
            return

        self.websocket.send(json.dumps(data))