Websocket on_message event handler

        Saves message as RTMMessage in self._inbox
337734
def on_message(self, ws, message):
        
        try:
            data = json.loads(message)
        except Exception:
            self._set_error(message, "decode message failed")
        else:
            self._inbox.put(RTMMessage(data))
904164
function onStringMessage(data)
    {
        try
        {
            data = (scope.encode) ? JSON.parse(atob(data)) : JSON.parse(data);
        
            switch(data.ev)
            {
                case InternalEvents.REDIRECT:
                {
                    changeServer(data.data);
                    break;
                }
                case InternalEvents.CONNECTED:
                {
                    scope.id = data.data;
                    if(scope.onConnected)
                    {
                        scope.onConnected(scope.id);
                    }
                    break;
                }
                case InternalEvents.JOINED_ROOM:
                {
                    scope.roomUsers   = data.data.users;
                    scope.room        = data.data.room;
                    scope.params      = data.data.params;
                    scope.rtcId       = data.data.rtcId;
                    scope.useRTC      = data.data.useRTC;
                    scope.rtcFallback = data.data.rtcFallback;
                    scope.byteType    = data.data.byteType;

                    if(scope.onJoinedRoom)
                    {
                        scope.onJoinedRoom(scope.room,scope.params);
                    }
                    break;
                }
                case InternalEvents.ROOM_PARAMS:
                {
                    scope.params = data.data;
                    if(scope.onRoomUpdate)
                    {
                        scope.onRoomUpdate(scope.params);
                    }
                    break;
                }
                case InternalEvents.USER_JOINED_ROOM:
                {
                    if(scope.roomUsers)
                    {
                        var hasObject = false;
                        for(var num = 0; num < scope.roomUsers.length; num++)
                        {
                            if(scope.roomUsers[num].id==data.data.id)
                            {
                                hasObject = true;
                                break;
                            }
                        }
                        if(hasObject == false)
                        {
                            scope.roomUsers.push(data.data);
                        }
                    }
                    if(scope.onClientJoinedRoom)
                    {
                        scope.onClientJoinedRoom(data.data.id);
                    }
                    break;
                }
                case InternalEvents.LEFT_ROOM:
                {
                    if(scope.roomUsers)
                    {
                        scope.roomUsers = [];
                    }
                    if(scope.onLeftRoom)
                    {
                        scope.onLeftRoom();
                    }
                    break;
                }
                case InternalEvents.USER_LEFT_ROOM:
                {
                    if(scope.roomUsers)
                    {
                        for(var num = 0; num < scope.roomUsers.length; num++)
                        {
                            if(scope.roomUsers[num].id==data.data)
                            {
                                scope.roomUsers.splice(num,1);
                                break;
                            }
                        }
                    }
                    if(scope.onClientLeftRoom)
                    {
                        scope.onClientLeftRoom(data.data);
                    }
                    break;
                }
                case InternalEvents.SDP_DESCRIPTION:
                {
                    if(scope.onSDPDescription)
                    {
                        scope.onSDPDescription(data.id,data.rtcId,data.data);
                    }
                    break;
                }
                case InternalEvents.ICE_CANDIDATE:
                {
                    if(scope.onIceCandidate)
                    {
                        scope.onIceCandidate(data.id,data.data);
                    }
                    break;
                }
                case InternalEvents.RTC_FALLBACK_LIST:
                {
                    scope.fallbackUsers = data.data;
                    
                    break;
                }
                case InternalEvents.RTC_FALLBACK:
                {
                    if(scope.onRTCFallback)
                    {
                        scope.onRTCFallback(data.from,data.data,false);
                    }
                    break;
                }
                case InternalEvents.PING:
                {
                    scope.send("0",MessageType.PING);
                    break;
                }
                default:
                {
                    if(data.ev)
                    {
                        if(scope.onMessage)
                        {
                            scope.onMessage(data);
                        }
                    }
                    else
                    {
                        if(scope.onRawMessage)
                        {
                            scope.onRawMessage(data);
                        }
                    }
                    break;
                }
            }
        }
        catch(e)
        {
            if(scope.onRawMessage)
            {
                scope.onRawMessage(data);
            }
        }
    }
1236268
function onServerMessage(message, rinfo) {

	var packet,
	    respond;

	alchemy.setStatus('multicast_messages', ++messages);

	try {
		packet = bson.deserialize(message);
	} catch(err) {
		log.warn('Received corrupt multicast message from ' + rinfo.address);
		return;
	}

	// Ignore packets that come from here
	if (packet.origin == alchemy.discovery_id) {
		return;
	}

	packet.remote = rinfo;

	if (packet.respond) {
		respond = function respond(data) {

			var response_packet = {
				type         : 'response',
				response_to  : packet.id,
				data         : data
			};

			submit(response_packet);
		};
	}

	// Emit it as a multicast event
	alchemy.emit('multicast', packet, respond, null);

	if (packet.response_to) {
		if (typeof callbacks[packet.response_to] === 'function') {
			callbacks[packet.response_to](packet.data, packet);
		}
	} else {
		// Emit it for multicast listeners only
		mevents.emit(packet.type, packet.data, packet, respond, null);
	}
}
489288
def on_message(self, new_data):
        """"""
        # https://github.com/socketio/engine.io-protocol

        LOGGER.debug("new frame [%r]", new_data)
        try:
            what = int(new_data[0])
            data = new_data[1:]
            data = data and from_json(data)
            if what == 0:
                self.ping_interval = float(data["pingInterval"]) / 1000
                LOGGER.debug("adjusted ping interval")
                return

            if what == 1:
                LOGGER.debug("received close")
                self.reraise(IOError("Connection closed remotely"))
                return

            if what == 3:
                self.__lastpong = time.time()
                LOGGER.debug("received a pong")
                return

            if what == 4:
                self._on_frame(data)
                return

            if what == 6:
                LOGGER.debug("received noop")
                self.send_message("5")
                return

            LOGGER.debug("unhandled message: [%d] [%r]", what, data)
        except Exception as ex:
            self.reraise(ex)
693661
function (ws, message) {
  let clientMessage;

  try {
    clientMessage = JSON.parse(message);
    /* jshint ignore:start */
    if (_.get(clientMessage, 'type') === 'message') {
      ws.send(JSON.stringify({
        ok: true,
        reply_to: _.get(clientMessage, 'id'),
        ts: Date.now(),
        message: _.get(clientMessage, 'text', message),
        type: _.get(clientMessage, 'type', 'message'),
        user: _.get(clientMessage, 'user', 'U1234567'),
        channel: _.get(clientMessage, 'channel', 'C1234567'),
      }));
    }
    /* jshint ignore:end */
  } catch (err) {
    logger.info('Invalid socket data ', message);
  }
}
334161
async def handle_control_event(self, message):
        
        cmd = message[WorkerProtocol.COMMAND]
        logger.debug(__("Manager worker got channel command '{}'.", cmd))

        # Prepare settings for use; Django overlaid by state overlaid by
        # anything immediate in the current packet.
        immediates = {}
        if cmd == WorkerProtocol.COMMUNICATE:
            immediates = message.get(WorkerProtocol.COMMUNICATE_SETTINGS, {}) or {}
        override = self.state.settings_override or {}
        override.update(immediates)
        self.settings_actual = self._marshal_settings()
        self.settings_actual.update(override)

        if cmd == WorkerProtocol.COMMUNICATE:
            try:
                await database_sync_to_async(self._data_scan)(**message[WorkerProtocol.COMMUNICATE_EXTRA])
            except Exception:
                logger.exception("Unknown error occured while processing communicate control command.")
                raise
            finally:
                await self.sync_counter.dec('communicate')

        elif cmd == WorkerProtocol.FINISH:
            try:
                data_id = message[WorkerProtocol.DATA_ID]
                data_location = DataLocation.objects.get(data__id=data_id)
                if not getattr(settings, 'FLOW_MANAGER_KEEP_DATA', False):
                    try:
                        def handle_error(func, path, exc_info):
                            """Handle permission errors while removing data directories."""
                            if isinstance(exc_info[1], PermissionError):
                                os.chmod(path, 0o700)
                                shutil.rmtree(path)

                        # Remove secrets directory, but leave the rest of the runtime directory
                        # intact. Runtime directory will be removed during data purge, when the
                        # data object is removed.
                        secrets_dir = os.path.join(
                            self._get_per_data_dir('RUNTIME_DIR', data_location.subpath),
                            ExecutorFiles.SECRETS_DIR
                        )
                        shutil.rmtree(secrets_dir, onerror=handle_error)
                    except OSError:
                        logger.exception("Manager exception while removing data runtime directory.")

                if message[WorkerProtocol.FINISH_SPAWNED]:
                    await database_sync_to_async(self._data_scan)(**message[WorkerProtocol.FINISH_COMMUNICATE_EXTRA])
            except Exception:
                logger.exception(
                    "Unknown error occured while processing finish control command.",
                    extra={'data_id': data_id}
                )
                raise
            finally:
                await self.sync_counter.dec('executor')

        elif cmd == WorkerProtocol.ABORT:
            await self.sync_counter.dec('executor')

        else:
            logger.error(__("Ignoring unknown manager control command '{}'.", cmd))
1304262
private void sendMessage(RTMPMessage messageIn) {
        IRTMPEvent eventIn = messageIn.getBody();
        IRTMPEvent event;
        switch (eventIn.getDataType()) {
            case Constants.TYPE_AGGREGATE:
                event = new Aggregate(((Aggregate) eventIn).getData());
                break;
            case Constants.TYPE_AUDIO_DATA:
                event = new AudioData(((AudioData) eventIn).getData());
                break;
            case Constants.TYPE_VIDEO_DATA:
                event = new VideoData(((VideoData) eventIn).getData());
                break;
            default:
                event = new Notify(((Notify) eventIn).getData());
                break;
        }
        // get the incoming event time
        int eventTime = eventIn.getTimestamp();
        // get the incoming event source type and set on the outgoing event
        event.setSourceType(eventIn.getSourceType());
        // instance the outgoing message
        RTMPMessage messageOut = RTMPMessage.build(event, eventTime);
        if (log.isTraceEnabled()) {
            log.trace("Source type - in: {} out: {}", eventIn.getSourceType(), messageOut.getBody().getSourceType());
            long delta = System.currentTimeMillis() - playbackStart;
            log.trace("sendMessage: streamStartTS {}, length {}, streamOffset {}, timestamp {} last timestamp {} delta {} buffered {}", new Object[] { streamStartTS.get(), currentItem.get().getLength(), streamOffset, eventTime, lastMessageTs, delta, lastMessageTs - delta });
        }
        if (playDecision == 1) { // 1 == vod/file
            if (eventTime > 0 && streamStartTS.compareAndSet(-1, eventTime)) {
                log.debug("sendMessage: set streamStartTS");
                messageOut.getBody().setTimestamp(0);
            }
            long length = currentItem.get().getLength();
            if (length >= 0) {
                int duration = eventTime - streamStartTS.get();
                if (log.isTraceEnabled()) {
                    log.trace("sendMessage duration={} length={}", duration, length);
                }
                if (duration - streamOffset >= length) {
                    // sent enough data to client
                    stop();
                    return;
                }
            }
        } else {
            // don't reset streamStartTS to 0 for live streams
            if (eventTime > 0 && streamStartTS.compareAndSet(-1, eventTime)) {
                log.debug("sendMessage: set streamStartTS");
            }
            // relative timestamp adjustment for live streams
            int startTs = streamStartTS.get();
            if (startTs > 0) {
                // subtract the offset time of when the stream started playing for the client
                eventTime -= startTs;
                messageOut.getBody().setTimestamp(eventTime);
                if (log.isTraceEnabled()) {
                    log.trace("sendMessage (updated): streamStartTS={}, length={}, streamOffset={}, timestamp={}", new Object[] { startTs, currentItem.get().getLength(), streamOffset, eventTime });
                }
            }
        }
        doPushMessage(messageOut);
    }
1179300
function tclog(message, attrs) {
            var str = "##teamcity[" + message;
            if (typeof(attrs) === "object") {
                if (!("timestamp" in attrs)) {
                    attrs.timestamp = new Date();
                }
                for (var prop in attrs) {
                    if (attrs.hasOwnProperty(prop)) {
                        if(delegates.modifySuiteName && message.indexOf("testSuite") === 0 && prop === "name") {
                            attrs[prop] = delegates.modifySuiteName(attrs[prop]);
                        }
                        str += " " + prop + "='" + escapeTeamCityString(attrs[prop]) + "'";
                    }
                }
            }
            str += "]";
            log(str);
        }
373621
def on_message(self, ws, reply, *args):
        
        log.debug("Received message: %s" % str(reply))
        data = {}
        try:
            data = json.loads(reply, strict=False)
        except ValueError:
            raise ValueError("API node returned invalid format. Expected JSON!")

        if data.get("method") == "notice":
            id = data["params"][0]

            if id >= len(self.__events__):
                log.critical("Received an id that is out of range\n\n" + str(data))
                return

            # This is a "general" object change notification
            if id == self.__events__.index("on_object"):
                # Let's see if a specific object has changed
                for notice in data["params"][1]:
                    try:
                        if "id" in notice:
                            self.process_notice(notice)
                        else:
                            for obj in notice:
                                if "id" in obj:
                                    self.process_notice(obj)
                    except Exception as e:
                        log.critical(
                            "Error in process_notice: {}\n\n{}".format(
                                str(e), traceback.format_exc
                            )
                        )
            else:
                try:
                    callbackname = self.__events__[id]
                    log.info("Patching through to call %s" % callbackname)
                    [getattr(self.events, callbackname)(x) for x in data["params"][1]]
                except Exception as e:
                    log.critical(
                        "Error in {}: {}\n\n{}".format(
                            callbackname, str(e), traceback.format_exc()
                        )
                    )
341853
function _onMessage(message) {
        var response    = JSON.parse(message.data),
            msgRecord   = _messageCallbacks[response.id],
            callback    = msgRecord && msgRecord.callback,
            msgText     = (msgRecord && msgRecord.message) || "No message";

        if (msgRecord) {
            // Messages with an ID are a response to a command, fire callback
            callback(response.result, response.error);
            delete _messageCallbacks[response.id];
        } else if (response.method) {
            // Messages with a method are an event, trigger event handlers
            var domainAndMethod = response.method.split("."),
                domain = domainAndMethod[0],
                method = domainAndMethod[1];

            EventDispatcher.triggerWithArray(exports[domain], method, response.params);
        }

        // Always fire event handlers for all messages/errors
        exports.trigger("message", response);

        if (response.error) {
            exports.trigger("error", response.error, msgText);
        }
    }
92493
function _window_onMessage(event){
        var origin = _getOrigin(event);
        if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") {
            pub.up.incoming(event.data.substring(config.channel.length + 1), origin);
        }
    }
1021450
function onMessage(message) {
    if (message.type != "utf8") return

    DEBUGMSG("recv: " + message.utf8Data)
    message = JSON.parse(message.utf8Data)

    if      (message.type == "request")  session.onRequest(channel, message)
    else if (message.type == "response") session.onResponse(channel, message)
    else if (message.type == "event")    session.onEvent(channel, message)
  }
877086
async def on_message(self, event):
        
        # We want to show only messages sent to this chat
        if event.chat_id != self.chat_id:
            return

        # Save the message ID so we know which to reply to
        self.message_ids.append(event.id)

        # Decide a prefix (">> " for our messages, "<user>" otherwise)
        if event.out:
            text = '>> '
        else:
            sender = await event.get_sender()
            text = '<{}> '.format(sanitize_str(
                utils.get_display_name(sender)))

        # If the message has media show "(MediaType) "
        if event.media:
            text += '({}) '.format(event.media.__class__.__name__)

        text += sanitize_str(event.text)
        text += '\n'

        # Append the text to the end with a newline, and scroll to the end
        self.log.insert(tkinter.END, text)
        self.log.yview(tkinter.END)
922417
async def message_handler(self, event):
        """"""

        # Note that message_handler is called when a Telegram update occurs
        # and an event is created. Telegram may not always send information
        # about the ``.sender`` or the ``.chat``, so if you *really* want it
        # you should use ``get_chat()`` and ``get_sender()`` while working
        # with events. Since they are methods, you know they may make an API
        # call, which can be expensive.
        chat = await event.get_chat()
        if event.is_group:
            if event.out:
                sprint('>> sent "{}" to chat {}'.format(
                    event.text, get_display_name(chat)
                ))
            else:
                sprint('<< {} @ {} sent "{}"'.format(
                    get_display_name(await event.get_sender()),
                    get_display_name(chat),
                    event.text
                ))
        else:
            if event.out:
                sprint('>> "{}" to user {}'.format(
                    event.text, get_display_name(chat)
                ))
            else:
                sprint('<< {} sent "{}"'.format(
                    get_display_name(chat), event.text
                ))
1304401
@Override
  public void onMessage(WebSocket webSocket, String message) {
    JsonObject json = new JsonParser().parse(message).getAsJsonObject();
    if (json.has(ERROR)) {
      String error = json.get(ERROR).getAsString();

      // Only call onError() if a real error occurred. The STT service sends
      // {"error" : "No speech detected for 5s"} for valid timeouts, configured by
      // RecognizeUsingWebSocketOptions.Builder.inactivityTimeout()
      if (!error.startsWith(TIMEOUT_PREFIX)) {
        callback.onError(new RuntimeException(error));
      } else {
        // notify that the service timeouts because of inactivity
        callback.onInactivityTimeout(new RuntimeException(error));
      }
    } else if (json.has(RESULTS) || json.has(SPEAKER_LABELS)) {
      callback.onTranscription(GSON.fromJson(message, SpeechRecognitionResults.class));

    } else if (json.has(STATE)) {
      // A listen state after everything has been sent over indicates everything has been processed
      if (!isListening) {
        isListening = true;
      } else {
        callback.onTranscriptionComplete();
        socket.close(CLOSE_NORMAL, "Transcription completed");
        return;
      }

      // notify that the service is ready to receive audio
      callback.onListening();
    }
  }
810954
def _generic_signal_handler(self, signal_type):
        
        print("</pre>")
        message = "Got " + signal_type + ". Failing gracefully..."
        self.timestamp(message)
        self.fail_pipeline(KeyboardInterrupt(signal_type), dynamic_recover=True)
        sys.exit(1)
935864
@Override
	public void handleMessageToClient(WebSocketSession session, Message<?> message) {
		if (!(message instanceof WampMessage)) {
			logger.error("Expected WampMessage. Ignoring " + message + ".");
			return;
		}

		boolean closeWebSocketSession = false;
		try {
			String json = ((WampMessage) message).toJson(this.jsonFactory);
			session.sendMessage(new TextMessage(json));
		}
		catch (SessionLimitExceededException ex) {
			// Bad session, just get out
			throw ex;
		}
		catch (Throwable ex) {
			// Could be part of normal workflow (e.g. browser tab closed)
			logger.debug("Failed to send WebSocket message to client in session "
					+ session.getId() + ".", ex);
			closeWebSocketSession = true;
		}
		finally {
			if (closeWebSocketSession) {
				try {
					session.close(CloseStatus.PROTOCOL_ERROR);
				}
				catch (IOException ex) {
					// Ignore
				}
			}
		}
	}