Enqueue a message to be written once handshaking is complete.
183018
public synchronized void enqueueWriteRequest(final NextFilter nextFilter,
            final WriteRequest writeRequest) {
        if (writeRequestQueue == null) {
            writeRequestQueue = new LinkedList<>();
        }

        writeRequestQueue.offer(new Event(nextFilter, writeRequest));
    }
820425
def send(self, message):
        
        assert self._handshake_performed, "Perform a handshake first."
        assert message.message_type in self.CALL_REQ_TYPES, (
            "Message '%s' can't use send" % repr(message)
        )

        message.id = message.id or self.writer.next_message_id()
        assert message.id not in self._outbound_pending_call, (
            "Message ID '%d' already being used" % message.id
        )

        future = tornado.gen.Future()
        self._outbound_pending_call[message.id] = future
        self.write(message)
        return future
1231335
def __on_message(self, connection, sender, message):
        
        if message.strip() == '!bot send':
            cycle = itertools.cycle(string.digits)
            content = ''.join(next(cycle) for _ in range(100))
            self.send_message(sender, content)

        else:
            parts = message.split(':', 2)
            if not parts or parts[0] != 'HRLD':
                return

            if parts[1] == 'BEGIN':
                # Beginning of multi-line message
                self._queue[parts[2]] = []

            elif parts[1] == 'END':
                # End of multi-line message
                content = ''.join(self._queue.pop(parts[2]))
                self.__notify(sender, content)

            elif parts[1] == 'MSG':
                # Single-line message
                content = parts[2]
                self.__notify(sender, content)

            else:
                # Multi-line message continuation
                uid = parts[1]
                self._queue[uid].append(parts[2])
1170968
private void doQueueOffer(final Message<JsonObject> message) {
    final String name = message.body().getString("name");
    if (name == null) {
      message.reply(new JsonObject().putString("status", "error").putString("message", "No name specified."));
      return;
    }

    final Object value = message.body().getValue("value");
    if (value == null) {
      message.reply(new JsonObject().putString("status", "error").putString("message", "No value specified."));
      return;
    }

    context.execute(new Action<Boolean>() {
      @Override
      public Boolean perform() {
        return data.getQueue(formatKey(name)).offer(value);
      }
    }, new Handler<AsyncResult<Boolean>>() {
      @Override
      public void handle(AsyncResult<Boolean> result) {
        if (result.failed()) {
          message.reply(new JsonObject().putString("status", "error").putString("message", result.cause().getMessage()));
        } else {
          message.reply(new JsonObject().putString("status", "ok").putBoolean("result", result.result()));
        }
      }
    });
  }
461111
def start_handshake(self, timeout):
        
        if not self.__timer:
            self.__timer = threading.Timer(float(timeout), self.read_timer)
            self.__timer.start()
394242
protected void flushQueuedMessages(IoSession session, AttachedSessionManager attachedSessionManager) {
        Queue<Object> messageQueue = getMessageQueue(session);
        if (messageQueue != null) {
            flushQueuedMessages(messageQueue, session, attachedSessionManager);
            // Note: leave messageQueue intact on session to avoid race condition
            // will be cleared by next received message anyway
        }
    }
579726
def send(self, msg):
        """"""
        if self._req_ctx is not None:
            self._send(msg)
        else:
            self._send_queue.put(msg)
            self._event.set()
1016554
def enqueue(self, item_type, item):
        """"""

        with self.enlock:
            self.queue[item_type].append(item)
631476
function _handshake(retry) {
            // Remove load handler if needed
            _removeTimer.call(this, true);

            if (!this.disposed && !this.ready) {
                if (!_isNativeMessageChannelSupported.call(this)) {
                    this.targetOrigin = this.targetOrigin || PostMessageUtilities.resolveOrigin(this.target) || "*";
                }

                if (!this.hosted) {
                    if (_isNativeMessageChannelSupported.call(this)) {
                        try {
                            if (this.neutered) {
                                this.channelFactory();
                            }
                            this.target.contentWindow.postMessage(this.token, this.targetOrigin, [ this.dispatcher ]);
                            this.neutered = true;
                        }
                        catch(ex) {
                            /* istanbul ignore next  */
                            return false;
                        }
                    }
                    else {
                        this.target.contentWindow.postMessage(this.token, this.targetOrigin);
                    }
                }
            }

            if (!this.disposed && !this.ready && retry) {
                if (0 < this.handshakeAttempts) {
                    this.handshakeAttempts--;
                    this.rmtimer = PostMessageUtilities.delay(_handshake.bind(this, retry), retry);
                }
                else {
                    this.onready(new Error("Loading: Operation Timeout!"));
                }
            }

            return true;
        }
998616
function(id) {
        var q = queues[id], msg, sc;
        if (q.timer) {
            // q.timer.cancel();
            clearTimeout(q.timer);
        }
        q.finished = true;

        if (q.aborted) {
            msg = "transaction " + id + " was aborted";
            _fail(id, msg);
            return;
        }

        // execute success callback
        if (q.onSuccess) {
            sc = q.context || q;
            q.onSuccess.call(sc, _returnData(q));
        }

        _end(id, msg, 'OK');
    }
352833
def _handshake(self, conn, addr):
        '''
        
        '''
        # waiting for the magic request message
        msg = conn.recv(len(MAGIC_REQ))
        log.debug('Received message %s from %s', msg, addr)
        if msg != MAGIC_REQ:
            log.warning('%s is not a valid REQ message from %s', msg, addr)
            return
        log.debug('Sending the private key')
        conn.send(self.__key)
        # wait for explicit ACK
        log.debug('Waiting for the client to confirm')
        msg = conn.recv(len(MAGIC_ACK))
        if msg != MAGIC_ACK:
            return
        log.debug('Sending the signature key')
        conn.send(self.__sgn)
        # wait for explicit ACK
        log.debug('Waiting for the client to confirm')
        msg = conn.recv(len(MAGIC_ACK))
        if msg != MAGIC_ACK:
            return
        log.info('%s is now authenticated', addr)
        self.keep_alive(conn)
928183
function broadcastQueuedMessages() {
            var message;
            while (messageQueue.length) {
                message = messageQueue.shift();
                broadcast(message.name, message.data);
            }
            messageQueue = null;
        }
945478
def complete(self, msg):
        """"""
        if _debug: IOCB._debug("complete(%d) %r", self.ioID, msg)

        if self.ioController:
            # pass to controller
            self.ioController.complete_io(self, msg)
        else:
            # just fill in the data
            self.ioState = COMPLETED
            self.ioResponse = msg
            self.trigger()
565843
public void enqueue(SerialMessage serialMessage) {
		this.sendQueue.add(serialMessage);
		logger.debug("Enqueueing message. Queue length = {}", this.sendQueue.size());
	}
334310
def enqueue(self, queue_identifier: QueueIdentifier, message: Message):
        
        assert queue_identifier.recipient == self.receiver
        with self._lock:
            already_queued = any(
                queue_identifier == data.queue_identifier and message == data.message
                for data in self._message_queue
            )
            if already_queued:
                self.log.warning(
                    'Message already in queue - ignoring',
                    receiver=pex(self.receiver),
                    queue=queue_identifier,
                    message=message,
                )
                return
            timeout_generator = udp_utils.timeout_exponential_backoff(
                self.transport._config['retries_before_backoff'],
                self.transport._config['retry_interval'],
                self.transport._config['retry_interval'] * 10,
            )
            expiration_generator = self._expiration_generator(timeout_generator)
            self._message_queue.append(_RetryQueue._MessageData(
                queue_identifier=queue_identifier,
                message=message,
                text=json.dumps(message.to_dict()),
                expiration_generator=expiration_generator,
            ))
        self.notify()
1033974
public void sendHandshakeResponse(HandshakeResponse wsResponse) {
        log.debug("Writing handshake on session: {}", session.getId());
        // create write future
        handshakeWriteFuture = session.write(wsResponse);
        handshakeWriteFuture.addListener(new IoFutureListener<WriteFuture>() {

            @Override
            public void operationComplete(WriteFuture future) {
                IoSession sess = future.getSession();
                if (future.isWritten()) {
                    // handshake is finished
                    log.debug("Handshake write success! {}", sess.getId());
                    // set completed flag
                    sess.setAttribute(Constants.HANDSHAKE_COMPLETE);
                    // set connected state on ws connection
                    if (connected.compareAndSet(false, true)) {
                        try {
                            // send queued packets
                            queue.forEach(entry -> {
                                sess.write(entry);
                                queue.remove(entry);
                            });
                        } catch (Exception e) {
                            log.warn("Exception draining queued packets on session: {}", sess.getId(), e);
                        }
                    }
                } else {
                    log.warn("Handshake write failed from: {} to: {}", sess.getLocalAddress(), sess.getRemoteAddress());
                }
            }

        });
    }
1088850
def deliver_deferred(jid, message, type)
      msg = {:to => jid, :message => message, :type => type}
      queue(:pending_messages) << [msg]
    end