when the socket pings, so that we now new messages came,
run this
961559
async function handleMessagePing(state, msgObj) {

    /**
     * when there are no listener, we do nothing
     */
    if (!state.messagesCallback) return;

    let messages;
    if (!msgObj) {
        // get all
        messages = await getAllMessages(state.channelName, state.paths);
    } else {
        // get single message
        messages = [
            getSingleMessage(state.channelName, msgObj, state.paths)
        ];
    }

    const useMessages = messages
        .filter(msgObj => _filterMessage(msgObj, state))
        .sort((msgObjA, msgObjB) => msgObjA.time - msgObjB.time); // sort by time


    // if no listener or message, so not do anything
    if (!useMessages.length || !state.messagesCallback) return;

    // read contents
    await Promise.all(
        useMessages
        .map(
            msgObj => readMessage(msgObj).then(content => msgObj.content = content)
        )
    );

    useMessages.forEach(msgObj => {
        state.emittedMessagesIds.add(msgObj.token);

        if (state.messagesCallback) {
            // emit to subscribers
            state.messagesCallback(msgObj.content.data);
        }
    });
}
229033
def run(self):
        """"""
        while not self.stopped:
            try:
                # grab a message from queue
                message = self.gc100_client.queue.get(True, 5)
            except queue.Empty:
                _LOGGER.debug("message thread: no messages")
                continue

            _LOGGER.debug("message thread: " + str(message))

            # parse message
            split_message = str(message).split(',')
            if len(split_message) != 3:
                _LOGGER.error("can't parse server response")
                continue
            event, module_address, value = str(message).split(',')
            value = int(value)

            # make a copy of the current subscribers to keep this thread-safe
            current_subscribers = dict(self.gc100_client.subscribers)

            # send message to subscribers
            for subscriber_id in current_subscribers:
                # msg or op should match what we asked for
                subscriber = current_subscribers[subscriber_id]

                if event + "," + module_address == subscriber['event']:
                    subscriber['callback'](value)
                    if subscriber['permanent'] is False:
                        self.gc100_client.unsubscribe(subscriber_id)

            # signals to queue job is done
            self.gc100_client.queue.task_done()
73361
public void run() {

		try {
			while (true) {
				//server thread blocks until a client connects
				Socket socket = server.accept();

				System.out.println(new LogEntry("client (" + socket.getInetAddress().getHostAddress() + ") attempts to connect..."));
				Connection c = establishConnection(socket);
				updateConnectedClients(c);
			}
		} catch (IOException ioe) {
			System.out.println(new LogEntry("server forced to stop with message " + ioe.getClass().getName() + ' ' + ioe.getMessage()));
		} catch (Throwable t) {
			System.out.println(new LogEntry(Level.CRITICAL, "server forced to stop with message " + t.getClass().getName() + ' ' + t.getMessage(), t));
		}
	}
1137171
def on_pubmsg(self, connection, event):
        
        sender = self.get_nick(event.source)
        channel = event.target
        message = event.arguments[0]

        self.handle_message(connection, sender, channel, message)
1152434
def ping(self):
        

        if self.session.transitions.is_connected():
            yield from self._handler.mqtt_ping()
        else:
            self.logger.warning("MQTT PING request incompatible with current session state '%s'" %
                                self.session.transitions.state)
969820
def send_socket(self, message):
        
        if self.log_sends:
            start_time = time.time()
        try:
            self.send_message(message)
        except Exception as error:
            logger.error('error sending message {!r}: {}'.format(message, error))
        else:
            if self.log_sends:
                elapsed_time = time.time() - start_time
                logger.info('sent message {!r} to {}:{} in {:.03f} seconds'.format(
                        message, self.host, self.port, elapsed_time))
1264465
async def run(self):
        
        self._logger.info("Agent started")
        self.__backend_socket.connect(self.__backend_addr)

        # Tell the backend we are up and have `concurrency` threads available
        self._logger.info("Saying hello to the backend")
        await ZMQUtils.send(self.__backend_socket, AgentHello(self.__friendly_name, self.__concurrency, self.environments))
        self.__last_ping = time.time()

        run_listen = self._loop.create_task(self.__run_listen())

        self._loop.call_later(1, self._create_safe_task, self.__check_last_ping(run_listen))

        await run_listen
771384
def heartbeat(self):
        
        while not self.ws.closed:
            gevent.sleep(HEARTBEAT_DELAY)
            gevent.spawn(self.send, "ping")
254012
protected void tick ()
    {
        // if we're not connected, skip it
        if (_comm == null) {
            return;
        }

        long now = RunAnywhere.currentTimeMillis();
        if (_dcalc != null) {
            // if our current calculator is done, clear it out
            if (_dcalc.isDone()) {
                if (debugLogMessages()) {
                    log.info("Time offset from server: " + _serverDelta + "ms.");
                }
                _dcalc = null;
            } else if (_dcalc.shouldSendPing()) {
                // otherwise, send another ping
                PingRequest req = new PingRequest();
                _comm.postMessage(req);
                _dcalc.sentPing(req);
            }

        } else if (now - _comm.getLastWrite() > PingRequest.PING_INTERVAL) {
            // if we haven't sent anything over the network in a while, we ping the server to let
            // it know that we're still alive
            _comm.postMessage(new PingRequest());

        } else if (now - _lastSync > CLOCK_SYNC_INTERVAL) {
            // resync our clock with the server
            establishClockDelta(now);
        }
    }
498054
def run(self):  # Thread for receiving data from pilight
        """"""
        logging.debug('Pilight receiver thread started')
        if not self.callback:
            raise RuntimeError('No callback function set, cancel readout thread')

        def handle_messages(messages):
            """Call callback on each receive message."""
            for message in messages:  # Loop over received  messages
                if message:  # Can be empty due to splitlines
                    message_dict = json.loads(message.decode())
                    if self.recv_codes_only:
                        # Filter: Only use receiver messages
                        if 'receiver' in message_dict['origin']:
                            if self.veto_repeats:
                                if message_dict.get('repeats', 1) == 1:
                                    self.callback(message_dict)
                            else:
                                self.callback(message_dict)
                    else:
                        self.callback(message_dict)

        while not self._stop_thread.isSet():
            try:  # Read socket in a non blocking call and interpret data
                # Sometimes more than one JSON object is in the stream thus
                # split at \n
                with self._lock:
                    messages = self.receive_socket.recv(1024).splitlines()
                handle_messages(messages)
            except (socket.timeout, ValueError):  # No data
                pass
        logging.debug('Pilight receiver thread stopped')
80087
def run(self):
        """"""
        try:
            while True:
                message = self.connection.recv()
                result = self.on_message(message)
                if result:
                    self.connection.send(result)
        except SelenolWebSocketClosedException as ex:
            self.on_closed(0, '')
            raise SelenolWebSocketClosedException() from ex
1064066
def run(self):
        
        self._stop = False # Allow re-starting the event loop
        while not self._stop:
            try:
                self._buffer += self.socket.recv(4096)
            except socket.error:
                raise

            lines = self._buffer.split("\n")
            self._buffer = lines.pop() # Last line may not have been fully read
            for line in lines:
                line = line.rstrip("\r")
                _log.debug("%s --> %s", self.server.host, line)
                self.dispatch_event("LINE", line)
                self.dispatch_event("ACTIVITY")
28684
public void run(Socket socket) {
    synchronized (lock) {
      nextSocket = socket;
      lock.notify();
    }
    Thread.yield();
  }
1246732
def listen(self):
        

        # Make sure we're in server mode
        if self.mode and self.mode != 'server':
            raise ValueError("%s is not in server mode" %
                             self.__class__.__name__)
        self.mode = 'server'

        # Obtain a listening socket
        serv = _create_server(self.host, self.port)

        # If we have too many errors, we want to bail out
        err_thresh = 0
        while True:
            # Accept a connection
            try:
                sock, addr = serv.accept()
            except Exception as exc:
                err_thresh += 1
                if err_thresh >= self.max_err_thresh:
                    LOG.exception("Too many errors accepting "
                                  "connections: %s" % str(exc))
                    break
                continue  # Pragma: nocover

            # Decrement error count on successful connections
            err_thresh = max(err_thresh - 1, 0)

            # Log the connection attempt
            LOG.info("Accepted connection from %s port %s" %
                     (addr[0], addr[1]))

            # And handle the connection
            eventlet.spawn_n(self.serve, self.connection_class(sock), addr)

        # Close the listening socket
        with utils.ignore_except():
            serv.close()
424239
def on_receive(self, message):
        
        if self.log_file is not None and message['should_log']:
            message_copy = Message(message['text'],
                                   Metadata(None).__dict__,
                                   message['should_log']).__dict__
            with open(self.log_file, mode='w') as f:
                f.write(json.dumps(message_copy))
            logger.info(message['metadata']['source'])
        if self.listening_for(message):
            self_thread = self.HandlerThread(self.handle, message)
            self_thread.start()
        self.cleanup()
        for child in self.children:
            child.tell(message)
1134007
private void updateMessage(ClientSocket client, DataInputStream buffer, byte messageSystemId, byte from)
            throws IOException
    {
        switch (messageSystemId)
        {
            case NetworkMessageSystemId.CONNECTING:
                receiveConnecting(client, buffer, from, StateConnection.CONNECTING);
                break;
            case NetworkMessageSystemId.CONNECTED:
                receiveConnected(client, from, StateConnection.CONNECTED);
                break;
            case NetworkMessageSystemId.PING:
                client.getOut().writeByte(NetworkMessageSystemId.PING);
                client.getOut().flush();
                bandwidth += 1;
                break;
            case NetworkMessageSystemId.OTHER_CLIENT_DISCONNECTED:
                receiveDisconnected(client, from, StateConnection.CONNECTED);
                break;
            case NetworkMessageSystemId.OTHER_CLIENT_RENAMED:
                receiveRenamed(client, buffer, from, StateConnection.CONNECTED);
                break;
            case NetworkMessageSystemId.USER_MESSAGE:
                receiveMessage(client, buffer, from, StateConnection.CONNECTED);
                break;
            default:
                break;
        }
    }
1277616
def _listen(sockets):
    """"""
    while True:
        (i , o, e) = select.select(sockets.keys(),[],[],1)
        for socket in i:
            if isinstance(sockets[socket], Chatroom):
                data_len = sockets[socket].client.Process(1)
                if data_len is None or data_len == 0:
                    raise Exception('Disconnected from server')
            #elif sockets[socket] == 'stdio':
            #    msg = sys.stdin.readline().rstrip('\r\n')
            #    logger.info('stdin: [%s]' % (msg,))
            else:
                raise Exception("Unknown socket type: %s" % repr(sockets[socket]))