Server-side message from ZMQ
431897
public function onEntry($entry)
    {
        if (is_array($entry)) {
            // First item from laravel-zmq is the channel name
            $channel = $entry[0];

            // Second is the actual message (in JSON format)
            $entry = json_decode($entry[1], true);

            // Put the channel name back into the payload
            $entry['channel'] = $channel;

            // And re-encode so it can be sent to clients
            $entry = json_encode($entry);
        }

        // No channel found in the payload or channel doesn't have any subscribers
        if (! $channel || ! array_key_exists($channel, $this->subscribedTopics)) {
            return;
        }

        if (starts_with($channel, 'private-')) {
            // Only get the subscribers to the channel that this should be published on
            $subs = $this->subscribedTopics[$channel];

            foreach ($subs as $to) {
                $this->send($to, $entry);
            }
        } else {
            // If it's public, send to all clients
            $this->sendAll($entry);
        }
    }
908538
public function receive($maxMessages = null, $timeout = null, ZendQueue $queue = null)
    {
        $maxMessages = $maxMessages === null ? 1 : max(1, (int) $maxMessages);
        $timeout = (int) ($timeout === null ? self::RECEIVE_TIMEOUT_DEFAULT : $timeout);
        if ($queue === null) {
            $queue = $this->_queue;
        }
        $queueId = $this->getQueueId($queue->getName());

        $msgs = [];
        $microtime = microtime(true); // cache microtime
        $microtimeInt = (int) $microtime;

        // start transaction handling
        try {
            if ($maxMessages > 0) { // ZF-7666 LIMIT 0 clause not included.
                $this->db->beginTransaction();
                $statement = $this->db->prepare("
                    select *
                    from QueueMessages
                    where queue_id = ? and (handle is null or timeout + {$timeout} < {$microtimeInt})
                    limit {$maxMessages}
                    for update
                ");
                $statement->bindValue(1, $queueId);
                $r = $statement->execute();

                foreach ($statement->fetchAll() as $data) {
                    // setup our changes to the message
                    $data['handle'] = md5(uniqid(rand(), true));

                    // update the database
                    $count = $this->db->executeUpdate(
                        "
                            update QueueMessages
                            set handle = ?, timeout = ?
                            where message_id = ? and (handle is null or timeout + {$timeout} < {$microtimeInt})
                        ",
                        [$data['handle'], $microtime, $data['message_id']]
                    );

                    // we check count to make sure no other thread has gotten
                    // the rows after our select, but before our update.
                    if ($count > 0) {
                        $msgs[] = $data;
                    }
                }
                $this->db->commit();
            }
        } catch (Exception $e) {
            $this->db->rollback();
            throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
        }

        $options = [
            'queue' => $queue,
            'data' => $msgs,
            'messageClass' => $queue->getMessageClass(),
        ];

        $classname = $queue->getMessageSetClass();

        return new $classname($options);
    }
1012949
def emit(self, signal, message, analysis_id):
        

        log.debug('kernel {} zmq send ({}): {}'
                  ''.format(analysis_id, signal, message))
        self.zmq_publish.send(json.dumps({
            'analysis_id': analysis_id,
            'frame': {'signal': signal, 'load': message},
        }, default=json_encoder_default).encode('utf-8'))
1357177
function getSockets () {
  let _sub = zmq.socket('sub')
  let _pub = zmq.socket('pub')
  _pub.linger = 0

  _sub.subscribe('')
  _sub.on('message', (...args) => _pub.send(args))
  return {sub: _sub, pub: _pub}
}
206717
def recv(self, timeout=None):
        
        if timeout:
            try:
                testsock = self._zmq.select([self.socket], [], [], timeout)[0]
            except zmq.ZMQError as e:
                if e.errno == errno.EINTR:
                    testsock = None
                else:
                    raise
            if not testsock:
                return
            rv = self.socket.recv(self._zmq.NOBLOCK)
            return LogRecord.from_dict(json.loads(rv))
        else:
            return super(ZeroMQPullSubscriber, self).recv(timeout)
294985
def message(self, executor_id, slave_id, message):
        
        logging.info('Sends message `{}` to executor `{}` on slave `{}`'.format(
                     message, executor_id, slave_id))
        return self.driver.sendFrameworkMessage(encode(executor_id),
                                                encode(slave_id),
                                                message)
609653
public static ZMsg recvMsg(Socket socket, boolean wait)
    {
        return recvMsg(socket, wait ? 0 : ZMQ.DONTWAIT);
    }
753821
private function bootZmqConnection()
    {
        $this->info(sprintf('Starting ZMQ listener on: %s:%s', config('ratchet.zmq.host'), config('ratchet.zmq.port')));

        $context = new ZMQContext($this->getEventLoop());
        $socket = $context->getSocket(config('ratchet.zmq.method', \ZMQ::SOCKET_PULL));
        $socket->bind(sprintf('tcp://%s:%d', config('ratchet.zmq.host', '127.0.0.1'), config('ratchet.zmq.port', 5555)));

        $socket->on('messages', function ($messages) {
            $this->ratchetServer->onEntry($messages);
        });

        $socket->on('message', function ($message) {
            $this->ratchetServer->onEntry($message);
        });
    }
929602
def call(self, my_args=None):
        
        LOGGER.debug("zeromq.Publisher.call")
        if my_args is None:
            raise exceptions.ArianeConfError("publisher call arguments")
        if 'topic' not in my_args or my_args['topic'] is None or not my_args['topic']:
            raise exceptions.ArianeConfError("publisher topic")
        if 'msg' not in my_args or my_args['msg'] is None or not my_args['msg']:
            raise exceptions.ArianeConfError("publisher call msg")
        self.zmqsocket.send_string("%s %s" % (my_args['topic'], my_args['msg']))
648290
def on_message(self, message):
        
        log.debug('Got websocket message %s', message)
        if message == 'websocket client ready':
            if self.connected:
                # TBD: Add ability to run commands in this branch
                log.debug('Websocket already connected, returning')
                return

            self.connected = True

            evt_processor = event_processor.SaltInfo(self)
            client = salt.netapi.NetapiClient(self.application.opts)
            client.run({
                'fun': 'grains.items',
                'tgt': '*',
                'token': self.token,
                'mode': 'client',
                'asynchronous': 'local_async',
                'client': 'local'
                })
            while True:
                try:
                    event = yield self.application.event_listener.get_event(self)
                    evt_processor.process(event, self.token, self.application.opts)
                    # self.write_message('data: {0}\n\n'.format(salt.utils.json.dumps(event, _json_module=_json)))
                except Exception as err:
                    log.debug('Error! Ending server side websocket connection. Reason = %s', err)
                    break

            self.close()
        else:
            # TBD: Add logic to run salt commands here
            pass
950494
def publish_message(host, amqp_settings, routing_key, data, async=False):
    
    global _thread
    global _num_pending

    kwargs = {
        "host": host,
        "amqp_settings": amqp_settings,
        "routing_key": routing_key,
        "data": data
    }

    if not async:
        return _publish_message(**kwargs)

    if _thread is None:
        with _lock:
            if _thread is None:
                _thread = threading.Thread(target=_publish_messages_async)
                _thread.daemon = True
                _thread.start()

    with _lock:
        _num_pending += 1

    _queue.put(kwargs)
    return True
1187165
async def handle_client_message(self, client_addr, message):
        """"""

        # Verify that the client is registered
        if message.__class__ != ClientHello and client_addr not in self._registered_clients:
            await ZMQUtils.send_with_addr(self._client_socket, client_addr, Unknown())
            return

        message_handlers = {
            ClientHello: self.handle_client_hello,
            ClientNewJob: self.handle_client_new_job,
            ClientKillJob: self.handle_client_kill_job,
            ClientGetQueue: self.handle_client_get_queue,
            Ping: self.handle_client_ping
        }
        try:
            func = message_handlers[message.__class__]
        except:
            raise TypeError("Unknown message type %s" % message.__class__)
        self._create_safe_task(func(client_addr, message))
923306
def run(self):
        '''
        
        '''
        context = zmq.Context()
        # the socket for incoming cache requests
        creq_in = context.socket(zmq.REP)
        creq_in.setsockopt(zmq.LINGER, 100)
        creq_in.bind('ipc://' + self.cache_sock)

        # the socket for incoming cache-updates from workers
        cupd_in = context.socket(zmq.SUB)
        cupd_in.setsockopt(zmq.SUBSCRIBE, b'')
        cupd_in.setsockopt(zmq.LINGER, 100)
        cupd_in.bind('ipc://' + self.update_sock)

        # the socket for the timer-event
        timer_in = context.socket(zmq.SUB)
        timer_in.setsockopt(zmq.SUBSCRIBE, b'')
        timer_in.setsockopt(zmq.LINGER, 100)
        timer_in.connect('ipc://' + self.upd_t_sock)

        poller = zmq.Poller()
        poller.register(creq_in, zmq.POLLIN)
        poller.register(cupd_in, zmq.POLLIN)
        poller.register(timer_in, zmq.POLLIN)

        # our serializer
        serial = salt.payload.Serial(self.opts.get('serial', ''))

        # register a signal handler
        signal.signal(signal.SIGINT, self.signal_handler)

        # secure the sockets from the world
        self.secure()

        log.info('ConCache started')

        while self.running:

            # we check for new events with the poller
            try:
                socks = dict(poller.poll(1))
            except KeyboardInterrupt:
                self.stop()
            except zmq.ZMQError as zmq_err:
                log.error('ConCache ZeroMQ-Error occurred')
                log.exception(zmq_err)
                self.stop()

            # check for next cache-request
            if socks.get(creq_in) == zmq.POLLIN:
                msg = serial.loads(creq_in.recv())
                log.debug('ConCache Received request: %s', msg)

                # requests to the minion list are send as str's
                if isinstance(msg, six.string_types):
                    if msg == 'minions':
                        # Send reply back to client
                        reply = serial.dumps(self.minions)
                        creq_in.send(reply)

            # check for next cache-update from workers
            if socks.get(cupd_in) == zmq.POLLIN:
                new_c_data = serial.loads(cupd_in.recv())
                # tell the worker to exit
                #cupd_in.send(serial.dumps('ACK'))

                # check if the returned data is usable
                if not isinstance(new_c_data, list):
                    log.error('ConCache Worker returned unusable result')
                    del new_c_data
                    continue

                # the cache will receive lists of minions
                # 1. if the list only has 1 item, its from an MWorker, we append it
                # 2. if the list contains another list, its from a CacheWorker and
                #    the currently cached minions are replaced with that list
                # 3. anything else is considered malformed

                try:

                    if not new_c_data:
                        log.debug('ConCache Got empty update from worker')
                        continue

                    data = new_c_data[0]

                    if isinstance(data, six.string_types):
                        if data not in self.minions:
                            log.debug('ConCache Adding minion %s to cache',
                                      new_c_data[0])
                            self.minions.append(data)

                    elif isinstance(data, list):
                        log.debug('ConCache Replacing minion list from worker')
                        self.minions = data

                except IndexError:
                    log.debug('ConCache Got malformed result dict from worker')
                    del new_c_data

                log.info('ConCache %s entries in cache', len(self.minions))

            # check for next timer-event to start new jobs
            if socks.get(timer_in) == zmq.POLLIN:
                sec_event = serial.loads(timer_in.recv())

                # update the list every 30 seconds
                if int(sec_event % 30) == 0:
                    cw = CacheWorker(self.opts)
                    cw.start()

        self.stop()
        creq_in.close()
        cupd_in.close()
        timer_in.close()
        context.term()
        log.debug('ConCache Shutting down')
1092283
def check_skypipe_endpoint(endpoint, timeout=10):
    
    socket = ctx.socket(zmq.DEALER)
    socket.linger = 0
    socket.connect(endpoint)
    socket.send_multipart(sp_msg(SP_CMD_HELLO))
    timeout_time = time.time() + timeout
    while time.time() < timeout_time:
        reply = None
        try:
            reply = socket.recv_multipart(zmq.NOBLOCK)
            break
        except zmq.ZMQError:
            time.sleep(0.1)
    socket.close()
    if reply:
        return str(reply.pop(0)) == SP_HEADER
598425
function Message(payload, checksum, magic, compression){
  // note: payload should be a Buffer
  var _compression = COMPRESSION_DEFAULT;

  // compression:
  // 0 = none; 1 = gzip; 2 = snappy;
  // Only exists at all if MAGIC == 1
  if (!!magic && magic == 1){
    if (_.include([0,1,2], compression)){
      _compression = compression;
    } else {
      throw "InvalidCompressionType: " + compression;
    }
  }
  this.compression = _compression;
  this.MAGIC_IDENTIFIER_DEFAULT = 1;
  if (magic === undefined){ 
    this.magic = this.MAGIC_IDENTIFIER_DEFAULT;
  } else { 
    this.magic = magic;
  }
  if (this.magic !== 0 && this.magic !== 1){
    throw "Unsupported Kafka message version: " + this.magic;
  }
  if (!payload && payload !== ''){
    throw "payload is a required argument";
  }
  this.payload = payload;
  this.checksum = checksum || this.calculateChecksum();
}
169570
def _zmq_socket_context(context, socket_type, bind_endpoints):
    """"""
    socket = context.socket(socket_type)
    try:
        for endpoint in bind_endpoints:
            try:
                socket.bind(endpoint)
            except Exception:
                _logger.fatal("Could not bind to '%s'.", endpoint)
                raise
        yield socket
    finally:
        socket.close()
282640
public void sendMessage(String requestMessage, String queueName, String correlationId,
            final Queue replyQueue, int delaySeconds, int deliveryMode) throws JMSException {
        /**
         * If it's an internal message then always use jmsTemplate for ActiveMQ
         */

        if (jmsTemplate != null) {
            jmsTemplate.setDeliveryMode(deliveryMode);
            if (!StringUtils.isEmpty(queueName)) {
                jmsTemplate.send(queueName, new MDWMessageCreator(requestMessage, correlationId,
                        replyQueue, delaySeconds));

            }
            else {
                jmsTemplate.send(new MDWMessageCreator(requestMessage, correlationId, replyQueue));
            }
        }
    }