Receiving messages from cjdns admin server
430161
def _receiverThread(session):
    """"""

    timeOfLastSend = time.time()
    timeOfLastRecv = time.time()
    try:
        while True:
            if timeOfLastSend + KEEPALIVE_INTERVAL_SECONDS < time.time():
                if timeOfLastRecv + 10 < time.time():
                    raise exceptions.PingTimeout()
                session.socket.send(
                    b'd1:q18:Admin_asyncEnabled4:txid8:keepalive')
                timeOfLastSend = time.time()

            try:
                data = session.socket.recv(BUFFER_SIZE)
            except socket.timeout:
                continue

            try:
                benc = bdecode(data)
            except (KeyError, ValueError):
                logger.error("error decoding [%s]", data)
                continue

            if benc['txid'] == 'keepaliv':
                if benc['asyncEnabled'] == 0:
                    raise exceptions.SessionLost()
                timeOfLastRecv = time.time()
            else:
                session.queue.put(benc)

    except KeyboardInterrupt:
        logger.exception("interrupted")
        import thread
        thread.interrupt_main()
1119931
function(msg, node, RED, io, ioNs, log) {
        node.rcvMsgCount++
        log.verbose(`[${node.url}] msg received via FLOW. ${node.rcvMsgCount} messages received`, msg)

        // If the input msg is a uibuilder control msg, then drop it to prevent loops
        if ( msg.hasOwnProperty('uibuilderCtrl') ) return null

        //setNodeStatus({fill: 'yellow', shape: 'dot', text: 'Message Received #' + node.rcvMsgCount}, node)

        // Remove script/style content if admin settings don't allow
        if ( node.allowScripts !== true ) {
            if ( msg.hasOwnProperty('script') ) delete msg.script
        }
        if ( node.allowStyles !== true ) {
            if ( msg.hasOwnProperty('style') ) delete msg.style
        }

        // pass the complete msg object to the uibuilder client
        // TODO: This should have some safety validation on it!
        if (msg._socketId) {
            log.debug(`[${node.url}] msg sent on to client ${msg._socketId}. Channel: ${node.ioChannels.server}`, msg)
            ioNs.to(msg._socketId).emit(node.ioChannels.server, msg)
        } else {
            log.debug(`[${node.url}] msg sent on to ALL clients. Channel: ${node.ioChannels.server}`, msg)
            ioNs.emit(node.ioChannels.server, msg)
        }

        if (node.fwdInMessages) {
            // Send on the input msg to output
            node.send(msg)
            log.debug(`[${node.url}] msg passed downstream to next node`, msg)
        }

        return msg
    }
989347
private JSONObject publishHostId(
            InetSocketAddress hostAddr,
            MessagingChannel messagingChannel,
            Set<String> activeVersions) throws Exception
    {
        JSONObject jsObj = new JSONObject();
        jsObj.put(TYPE, ConnectionType.PUBLISH_HOSTID.name());
        jsObj.put(HOST_ID, m_localHostId);
        jsObj.put(PORT, m_internalPort);
        jsObj.put(ADDRESS,
                m_internalInterface.isEmpty() ? m_reportedInternalInterface : m_internalInterface);
        jsObj.put(VERSION_STRING, m_acceptor.getVersionChecker().getVersionString());

        jsObj = m_acceptor.decorate(jsObj, Optional.empty());
        jsObj.put(MAY_EXCHANGE_TS, true);

        byte[] jsBytes = jsObj.toString(4).getBytes(StandardCharsets.UTF_8);
        ByteBuffer pushHostId = ByteBuffer.allocate(4 + jsBytes.length);
        pushHostId.putInt(jsBytes.length);
        pushHostId.put(jsBytes).flip();
        messagingChannel.writeMessage(pushHostId);

        // read the json response from socketjoiner with version info and validate it
        return processJSONResponse(messagingChannel, activeVersions, true);
    }
1035156
def received_message(self, m):
        """"""

        # TODO: No support for binary messages
        m = str(m)
        logger.debug("Incoming upstream WS: %s", m)
        uwsgi.websocket_send(m)
        logger.debug("Send ok")
849893
protected void decodeMessage(byte type, byte from, byte dest, DataInputStream buffer) throws IOException
    {
        final NetworkMessage message = decoder.getNetworkMessageFromType(type);
        if (message != null)
        {
            final int skip = 3;
            if (buffer.skipBytes(skip) == skip)
            {
                message.decode(type, from, dest, buffer);
                messagesIn.add(message);
            }
        }
    }
1349123
@Override
	public final Message receive(long timeout) throws JMSException
    {
        if (messageListener != null)
            throw new FFMQException("Cannot receive messages while a listener is active","INVALID_OPERATION"); 
        
        AbstractMessage message = receiveFromDestination(timeout,true);
        if (message != null)
        {
        	message.ensureDeserializationLevel(MessageSerializationLevel.FULL);
        	
            message.setSession(session);
            
            // Auto acknowledge message
            if (autoAcknowledge)
                session.acknowledge();
        }
        return message;
    }
376893
function _broadcastMessage (type, data) {
    data = data || {}
    let message = {type, data}
    let { host, coordinationPort } = node.settings
    dns.resolve4(host, (err, addresses) => {
      if (err) {
        debug(`cannot resolve host '${host}'. Check DNS infrastructure.`)
        return
      }
      debug(`broadcasting message '${type}' to '${host}' nodes: ${addresses}`)
      addresses.forEach(address => {
        let messenger = zmq.socket('req')
        messenger.connect(`tcp://${address}:${coordinationPort}`)
        messenger.send(JSON.stringify({
          ...message,
          toAddress: address
        }))

        let _end = false
        function closeSocket () {
          if (_end) return
          _end = true
          messenger.close()
        }

        messenger.on('message', closeSocket)
        setTimeout(closeSocket, 300)
      })
    })
  }
1038990
public void sendDeliveredNotification(Jid to, String packetID) throws NotConnectedException, InterruptedException {
        // Create the message to send
        Message msg = new Message(to);
        // Create a MessageEvent Package and add it to the message
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setDelivered(true);
        messageEvent.setStanzaId(packetID);
        msg.addExtension(messageEvent);
        // Send the packet
        connection().sendStanza(msg);
    }
833538
@Override
	public final void messageReceived(final IoSession session, final Object message)
			throws Exception {
		final String str = message.toString();
		
		// Parse the command
		String cmd = null;
		final String[] args = str.trim().split("[\t ]");
		if (args.length>0) {
			cmd = args[0];
		}
		
		
		List<String> lstArg = new ArrayList<String>();
		if (args.length>0) {
			boolean isArg=false;
			int index=0;
			for (String val : args) {
				if (val.equals("-a")) {
					lstArg.add(val);
					index++;
					isArg=true;
				} else {
					if (val.length()>0) {
						if (isArg && val.charAt(0)!='-' && val.indexOf('=')==-1) {
							lstArg.set(index-1, lstArg.get(index-1)+" "+val);
						} else {
							lstArg.add(val);
							index++;
						}
					} else {
						lstArg.set(index-1, lstArg.get(index-1)+" ");
					}
				}
			}
		}
		
		// Try to launch the command
		final TcpCommand command = TcpIpCommands.getCommands().get(cmd);
		String result = null;
		
		// launch the command and get the result
		if (command != null) {
			if (args.length>1) {
				try {
				String[] finalArgs = new String[lstArg.size()];
				for (int i=0; i< finalArgs.length; i++) {
					String[] argSplit=lstArg.get(i).split("=");
					if (argSplit.length==2 && argSplit[1].charAt(0)=='"' && argSplit[1].charAt(argSplit[1].length()-1)=='"' ) {
						finalArgs[i]=argSplit[0]+"="+argSplit[1].substring(1, argSplit[1].length()-1);
					} else {
						finalArgs[i]=lstArg.get(i);
					}
				}
				result = command.process(session, Arrays.copyOfRange(finalArgs, 1, finalArgs.length));
				} catch (Exception e) {
					result = LaunchingMessageKind.ELAUNCH0007.format(cmd, e);
				}
			} else {
				result = command.process(session, new String[]{});
			}
		} else {
			session.write("command unknown :"+cmd);
		}
		// If the command returned a result, write it for the user
		if (result != null) {
			session.write(result);
		} else {
			session.write("");
		}
		session.write(ENDLINE);
		session.write(ENDLINE);
		session.write("> ");
	}
856379
public String getBroadcastMessageString() {

        CmsSessionInfo sessionInfo = OpenCms.getSessionManager().getSessionInfo(getSession());
        if (sessionInfo == null) {
            return null;
        }
        String sessionId = sessionInfo.getSessionId().toString();
        Buffer messageQueue = OpenCms.getSessionManager().getBroadcastQueue(sessionId);
        if (!messageQueue.isEmpty()) {
            // create message String
            StringBuffer result = new StringBuffer(512);
            // the user has pending messages, display them all
            while (!messageQueue.isEmpty()) {
                CmsBroadcast message = (CmsBroadcast)messageQueue.remove();
                result.append('[');
                result.append(getMessages().getDateTime(message.getSendTime()));
                result.append("] ");
                result.append(key(Messages.GUI_LABEL_BROADCASTMESSAGEFROM_0));
                result.append(' ');
                if (message.getUser() != null) {
                    result.append(message.getUser().getName());
                } else {
                    // system message
                    result.append(key(Messages.GUI_LABEL_BROADCAST_FROM_SYSTEM_0));
                }
                result.append(":\n");
                result.append(message.getMessage());
                result.append("\n\n");
            }
            return result.toString();
        }
        // no message pending, return null
        return null;
    }
105564
public Message receiveMessage()
    {
        Message message = null;
        try   {
            message = m_receiveQueue.receiveRemoteMessage();   // Hang until a message comes through
        } catch (RemoteException ex)    {
            ex.printStackTrace();
            return null;    // Remote exception = I'm done!
        }
        if (message instanceof BaseMessage)
            ((BaseMessage)message).setProcessedByServer(true);     // Don't send the message back down.
        return message;
    }
1096212
function(server, cb) {
    var port = _getServerConfig(server).port || 3223;
    var result = {running: false, port: port, listening: false};
    var host = 'localhost';

    var pidFile = path.join(nscaleRoot, 'data', '.' + server);

    portscanner.checkPortStatus(port, host, function(err, status) {
      if (err) { return cb(err); }
      result.listening = (status === 'open') ? true : false;

      if (fs.existsSync(pidFile)) {
        var pid = Number(fs.readFileSync(pidFile));
        result.pid = pid;

        running(pid, function(err, running) {
          if (err) { cb(err); }
          result.running = running;
          cb(null, result);
        });
      }
      else { 
        cb(null, result); 
      }
    });
  }
800169
function(self, agent, msg, cb) {
  logger.debug('[%s] receive addServer signal: %j', self.app.serverId, msg);
  if(!msg || !msg.server) {
    logger.warn('monitorwatcher addServer receive empty message: %j', msg);
    utils.invokeCallback(cb, Constants.SIGNAL.FAIL);
    return;
  }
  addServers(self, [msg.server]);
  utils.invokeCallback(cb, Constants.SIGNAL.OK);
}
500245
private void receiveMessage() {
		MessagingSystemInfo messagingSystemInfo = oneAgentSdk.createMessagingSystemInfo("DynatraceSample", "theQueue", MessageDestinationType.QUEUE, ChannelType.IN_PROCESS, null);
		IncomingMessageReceiveTracer incomingMessageReceiveTracer = oneAgentSdk.traceIncomingMessageReceive(messagingSystemInfo);
		incomingMessageReceiveTracer.start();
		try {
			Message msg = queueManager.receive("theQeue");
			if (msg == null) {
				return; // no message received
			}
			IncomingMessageProcessTracer incomingMessageProcessTracer = oneAgentSdk.traceIncomingMessageProcess(messagingSystemInfo);
			// store incoming tag to tracer:
			incomingMessageProcessTracer.setDynatraceStringTag(msg.getProperty(OneAgentSDK.DYNATRACE_MESSAGE_PROPERTYNAME));
			incomingMessageProcessTracer.setVendorMessageId(msg.getVendorMessageId());
						incomingMessageProcessTracer.start();
			try {
				// do something with the message ...
				System.out.println("Message received: " + msg.toString());
			} catch (Exception e) {
				incomingMessageProcessTracer.error(e);
			} finally {
				incomingMessageProcessTracer.end();
			}
			
			
		} catch (Exception e) {
			incomingMessageReceiveTracer.error(e);
		} finally {
			incomingMessageReceiveTracer.end();
		}
	}
1010380
protected void sendNoMessageToClient() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "sendNoMessageToClient");

        // Ensure that we set the flag that we have done all we can
        setCurrentlyDoingReceiveWithWait(false);
        setComplete(true);

        CommsServerByteBuffer buffer = poolManager.allocate();
        int msgLen = -1;
        ConversationState convState = (ConversationState) conversation.getAttachment();

        buffer.putShort(convState.getConnectionObjectId());
        if (!mainConsumer.getUsingConnectionReceive())
            buffer.putShort(mainConsumer.getConsumerSessionId());
        buffer.putLong(msgLen);

        int seg = JFapChannelConstants.SEG_RECEIVE_SESS_MSG_R;
        if (mainConsumer.getUsingConnectionReceive()) {
            seg = JFapChannelConstants.SEG_RECEIVE_CONN_MSG_R;
        }

        try {
            conversation.send(buffer,
                              seg,
                              requestNumber,
                              JFapChannelConstants.PRIORITY_MEDIUM,
                              true,
                              ThrottlingPolicy.BLOCK_THREAD,
                              null);
        } catch (SIException c) {
            FFDCFilter.processException(c, CLASS_NAME + ".sendNoMessageToClient",
                                        CommsConstants.CATSYNCASYNCHREADER_SEND_NO_MSG_01, this);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(tc, c.getMessage(), c);

            SibTr.error(tc, "COMMUNICATION_ERROR_SICO2015", c);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "sendNoMessageToClient");
    }
1189819
def receive(cmd_id, receive_timeout = nil)
      receive_timeout ||= timeout
      start = Time.now

      until @messages.key?(cmd_id)
        raise Errno::EWOULDBLOCK if (Time.now - start) >= receive_timeout
        if @receive_mutex.try_lock
          begin
            IO.select([socket], [], [], receive_timeout) || raise(Errno::EWOULDBLOCK)
            data = socket.recv(RECV_SIZE)
            break if data.empty?
            driver.parse(data)
          ensure
            @receive_mutex.unlock
          end
        else
          sleep(0.05)
        end
      end
      @messages.delete(cmd_id)
    end
617915
@RabbitListener(queues = "${hawkbit.dmf.rabbitmq.receiverQueue:dmf_receiver}", containerFactory = "listenerContainerFactory")
    public Message onMessage(final Message message,
            @Header(name = MessageHeaderKey.TYPE, required = false) final String type,
            @Header(name = MessageHeaderKey.TENANT, required = false) final String tenant) {
        return onMessage(message, type, tenant, getRabbitTemplate().getConnectionFactory().getVirtualHost());
    }