3. listener to handle incoming payload. 
The handle for client.on('take') on getting replies
@param  {JSON} msg Replied msg
 /* istanbul ignore next
483466
function handle(msg) {
  log.debug('handling msg', msg)
  var to = msg.to,
    intent = msg.intent;
  if (to && intent) {
    var reply;
    // try JSON or JSON.input as input
    try {
      reply = _.get(lib_js[to], intent)(msg)
    } catch (err) {
      try {
        reply = _.get(lib_js[to], intent)(msg.input)
      } catch (deepErr) {
        log.debug('js handle fails.', deepErr)
      }
    } finally {
      // try JSON or made-JSON output
      reply = correctReply(reply, msg)
      log.debug('reply', reply)
      if (reply.to) {
        client.emit('pass', reply)
      }
    }
  }
}
1030044
function _wrapMessageHandler(onmessage) {
            return function(message) {
                var msgObject;

                if (!message.origin || "*" === message.origin ||  this.targetOrigin === message.origin) {
                    if (_isHandshake.call(this, message) && !this.disposed && !this.hosted && !this.ready) {
                        _onReady.call(this);
                    }
                    else {
                        try {
                            msgObject = this.deserialize(message.data);

                            if (_validateToken.call(this, msgObject)) {
                                return onmessage && onmessage(msgObject);
                            }
                        }
                        catch (ex) {
                            msgObject = message.data || message;
                            PostMessageUtilities.log("Error while trying to handle the message", "ERROR", "PostMessageChannel");
                        }

                        return msgObject || message;
                    }
                }
            };
        }
1269708
def on_message_received(self, msg):
        
        if self.is_stopped:
            raise RuntimeError("reader has already been stopped")
        else:
            self.buffer.put(msg)
1055845
function onMessage(obj) {
    var id = obj.id;
    if (!self._matchesPrefix(id)) {
      debug('discarding unscoped message %s', id);
      return;
    }
    var cb = self._registry.get(id);
    if (cb) {
      process.nextTick(function () {
        debug('received message %s', id);
        // Ensure that the initial callback gets called asynchronously, even
        // for completely synchronous transports (otherwise the number of
        // pending requests will sometimes be inconsistent between stateful and
        // stateless transports).
        cb(null, Buffer.concat(obj.payload), self._adapter);
      });
    }
  }
177225
def _handle_response(self, msg_id, result=None, error=None):
        """"""
        request_future = self._server_request_futures.pop(msg_id, None)

        if not request_future:
            log.warn("Received response to unknown message id %s", msg_id)
            return

        if error is not None:
            log.debug("Received error response to message %s: %s", msg_id, error)
            request_future.set_exception(JsonRpcException.from_dict(error))

        log.debug("Received result for message %s: %s", msg_id, result)
        request_future.set_result(result)
897099
function handleMessage(data) {

      const message = data;

      message.params = that.parser.parse(data);
      message.channel = ch;
      message.ack = ack;

      // Ack method for the msg
      function ack() {
        debug('ack delivery', data.fields.deliveryTag);
        ch.ack(data);
      }

      if (Array.isArray(message)) {
        that.options.handler(message[0]);
      }
      else {
        that.options.handler(message);
      }
      debug('queue', that.options.queue);
      if (that.options.autoAck) {
        debug('autoAck', 'true');
        ack();
      }
    }
888642
def handle_req(msg):
    
    if not msg.gateway.is_sensor(msg.node_id, msg.child_id):
        return None
    value = msg.gateway.sensors[msg.node_id].children[
        msg.child_id].values.get(msg.sub_type)
    if value is not None:
        return msg.copy(
            type=msg.gateway.const.MessageType.set, payload=value)
    return None
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()
                        )
                    )
212267
function onmessage(packet) {
    if (arguments.length === 2) packet = arguments[1];
    packet = parse(packet);

    if (allowed(packet)) emit(packet);
  }
964251
def handle(handler, msg, sender, &block)
      @session.validate! sender if handler.validate?

      next_state, reply = handler.handle msg, @state, @session, sender

      return if abort_state_change?(next_state, &block)
      @state = next_state

      return unless reply

      sender.reply reply + "\r"
      logger.debug reply
    rescue Session::InvalidSender => e
      sender.reply "?\r"
      logger.warn e.message
    end
767162
function receive(msg) {
  var requests = [];
  var responses = [];

  if (!this.active) {
    return this;
  }

  // If we got JSON, parse it
  if (typeof msg === 'string') {
    try {
      msg = JSON.parse(msg);
    } catch (e) {
      // The specification doesn't force us to respond in error, ignoring
      return this;
    }
  }

  // If we get a standard single-type batch, dispatch it
  if (msg.constructor === Array) {
    if (msg.length === 0) {
      return this;
    }
    // Hint of request batch
    if (typeof msg[0].method === 'string') {
      requests = msg;
    } else {
      responses = msg;
    }
  } else if (typeof msg === 'object') {
    // Could we be a 'dual-batch' extended message?
    if (
      typeof msg.requests !== 'undefined'
      && typeof msg.responses !== 'undefined'
    ) {
      requests = msg.requests;
      responses = msg.responses;
    } else if (typeof msg.method === 'string') {
      // We're a single request
      requests.push(msg);
    } else {
      // We must be a single response
      responses.push(msg);
    }
  }

  responses.forEach(deliverResponse.bind(this));
  requests.forEach(serveRequest.bind(this));
  return this;
}
972076
def on_message(self, sender, content):
        
        try:
            message = json.loads(content)

        except (ValueError, TypeError) as ex:
            logging.error("Not a valid JSON string: %s", ex)
            return

        try:
            # Check the replied message
            reply_uid = message['reply-to']
            reply_level = message['reply-level']

        except KeyError:
            # Got a new message
            logging.info("Got message %s from %s", message['content'], sender)

            # Notify listeners
            self.__pool.enqueue(self._notify_listeners, sender, message)

        else:
            # Got a reply
            try:
                level, callback = self.__callbacks[reply_uid]

            except KeyError:
                # Nobody to callback...
                pass

            else:
                if level == reply_level:
                    # Match
                    try:
                        callback(sender, message['payload'])
                    except Exception as ex:
                        logging.exception("Error notifying sender: %s", ex)
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);
        }
    }
1335193
def _handle_msg(self, msg):
        """"""
        data = msg['content']['data']
        method = data['method']

        if method == 'update':
            if 'state' in data:
                state = data['state']
                if 'buffer_paths' in data:
                    _put_buffers(state, data['buffer_paths'], msg['buffers'])
                self.set_state(state)

        # Handle a state request.
        elif method == 'request_state':
            self.send_state()

        # Handle a custom msg from the front-end.
        elif method == 'custom':
            if 'content' in data:
                self._handle_custom_msg(data['content'], msg['buffers'])

        # Catch remainder.
        else:
            self.log.error('Unknown front-end to back-end widget msg with method "%s"' % method)
1344047
function handleMessages(event) {
  if (!isAllowed()) return;
  if (!event || event.source !== window || typeof event.data !== 'object') return;
  const message = event.data;
  if (message.source !== pageSource) return;
  if (message.type === 'DISCONNECT') {
    if (bg) {
      bg.disconnect();
      connected = false;
    }
    return;
  }

  tryCatch(send, message);
}
78163
def recv_msg(body,
             message):
    

    log.info(("callback received msg "))

    agg.handle_msg(
        body=body,
        org_message=message)
1004679
def _on_msg(self, msg):
        """"""
        data = msg['content']['data']

        # If the message is a call invoke, run the function and send
        # the results.
        if 'callback' in data:
            guid = data['callback']
            callback = callback_registry[guid]
            args = data['arguments']
            args = [self.deserialize(a) for a in args]
            index = data['index']

            results = callback(*args)
            return self.serialize(self._send('return', index=index, results=results))

        # The message is not a call invoke, it must be an object
        # that is a response to a Python request.
        else:
            index = data['index']
            immutable = data['immutable']
            value = data['value']
            if index in self._callbacks:
                self._callbacks[index].resolve({
                    'immutable': immutable,
                    'value': value
                })
                del self._callbacks[index]