Started by main() on a single thread, handle timing-out UDP packets
427216
public void run() {
    Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
    while( true ) {
      try {
        RPC t = PENDING.take();
        // One-shot timeout effect.  Retries need to re-insert back in the queue
        if( H2O.CLOUD.contains(t._target) ) {
          if( !t.isDone() ) t.call();
        } else t.cancel(true);
      } catch( InterruptedException e ) {
        // Interrupted while waiting for a packet?
        // Blow it off and go wait again...
      }
    }
  }
1214435
@Override
    public void run() {
        try {
            log.info("UDP - client started: " + this.hostname + ":" + this.port);
            isRunning = true;
            buf       = new ByteBuffer(5000);
            buf.setString(getInitMessage());    // A buffer size of 5000 to handle the server_param message.
            socket = new DatagramSocket();

            // Timeout of 3mins to ensure that the coach stays connected.
            socket.setSoTimeout(300000);
            DatagramPacket p = new DatagramPacket(buf.getByteArray(), buf.getByteArray().length,
                                   InetAddress.getByName(hostname), port);
            socket.send(p);
            socket.receive(p);
            this.host = p.getAddress();
            this.port = p.getPort();
            received(buf.getString());

            // Continue until the program is closed. This is where sserver messages are received.
            while (isRunning) {
                buf.reset();
                DatagramPacket packet = new DatagramPacket(buf.getByteArray(), buf.getByteArray().length);
                socket.receive(packet);
                received(buf.getString());
            }
        } catch (Exception ex) {
            log.error("Stopped running " + getName() + " " + getDescription() + " because: " + ex.toString());
        }

        // Clean up.
        socket.close();
        try {
            buf.close();
        } catch (IOException ex) {
            log.error("Error cleaning up thread - " + ex.getMessage());
        }
        try {
            this.finalize();
        } catch (Throwable ex) {
            log.error("Error cleaning up thread - " + ex.getMessage());
        }
        log.info("UDP - client terminated: " + this.hostname + ":" + this.port);
    }
440171
def main(args, stop=False):
    
    daemon = AMQPDaemon(
        con_param=getConParams(
            settings.RABBITMQ_STORAGE_VIRTUALHOST
        ),
        queue=settings.RABBITMQ_STORAGE_INPUT_QUEUE,
        out_exch=settings.RABBITMQ_STORAGE_EXCHANGE,
        out_key=settings.RABBITMQ_STORAGE_OUTPUT_KEY,
        react_fn=reactToAMQPMessage,
        glob=globals()                # used in deserializer
    )

    if not stop and args and args.foreground:  # run at foreground
        daemon.run()
    else:
        daemon.run_daemon()
1235155
def wait_running(self, timeout=None):
        

        flag = self._running.wait(timeout)

        if flag is False:
            raise TimeoutExpiredError("Timeout waiting for thread to start running")
63478
private void startBackgroundReceive() {
    // Read timeout, including heartbeats, should be handled by socket.
    // However Java Socket/Stream API does not enforce that. To stay on safer side,
    // use timeout on a future

    // let socket timeout first, set rough timeout to 110% of original
    long futureTimeout = heartbeatTimeoutMillis + heartbeatTimeoutMillis / 10;

    orchestratorExecutor.submit(
        () -> {
          NGClientDisconnectReason reason = NGClientDisconnectReason.INTERNAL_ERROR;
          try {
            LOG.log(Level.FINE, "Orchestrator thread started");
            while (true) {
              Future<Byte> readFuture;
              synchronized (orchestratorEvent) {
                if (shutdown) {
                  break;
                }
                readFuture =
                    readExecutor.submit(
                        () -> {
                          try {
                            return readChunk();
                          } catch (IOException e) {
                            throw new ExecutionException(e);
                          }
                        });
              }

              byte chunkType =
                  futureTimeout > 0
                      ? readFuture.get(futureTimeout, TimeUnit.MILLISECONDS)
                      : readFuture.get();

              if (chunkType == NGConstants.CHUNKTYPE_HEARTBEAT) {
                notifyHeartbeat();
              }
            }
          } catch (InterruptedException e) {
            LOG.log(Level.WARNING, "NGCommunicator orchestrator was interrupted", e);
          } catch (ExecutionException e) {
            Throwable cause = getCause(e);
            if (cause instanceof EOFException) {
              // DataInputStream throws EOFException if stream is terminated
              // just do nothing and exit main orchestrator thread loop
              LOG.log(Level.FINE, "Socket is disconnected");
              reason = NGClientDisconnectReason.SOCKET_ERROR;
            } else if (cause instanceof SocketTimeoutException) {
              reason = NGClientDisconnectReason.SOCKET_TIMEOUT;
              LOG.log(
                  Level.WARNING,
                  "Nailgun client socket timed out after " + heartbeatTimeoutMillis + " ms",
                  cause);
            } else {
              LOG.log(Level.WARNING, "Nailgun client read future raised an exception", cause);
            }
          } catch (TimeoutException e) {
            reason = NGClientDisconnectReason.HEARTBEAT;
            LOG.log(
                Level.WARNING,
                "Nailgun client read future timed out after " + futureTimeout + " ms",
                e);
          } catch (Throwable e) {
            LOG.log(Level.WARNING, "Nailgun orchestrator gets an exception ", e);
          }

          LOG.log(Level.FINE, "Nailgun client disconnected");

          // set client disconnected flag
          clientConnected.set(false);

          // notify stream readers there will be no more data
          setEof();

          // keep orchestrator thread running until signalled to shut up from close()
          // it is still responsible to notify about client disconnects if listener is
          // attached after disconnect had really happened
          waitTerminationAndNotifyClients(reason);

          LOG.log(Level.FINE, "Orchestrator thread finished");
        });
  }
996892
def main(router):
    
    argv = sys.argv[1:]
    if not len(argv):
        print('mitop: Need a list of SSH hosts to connect to.')
        sys.exit(1)

    delay = 2.0
    select = mitogen.select.Select(oneshot=False)
    hosts = []

    # For each hostname on the command line, create a Host instance, a Mitogen
    # connection, a Receiver to accept messages from the host, and finally
    # start child_main() on the host to pump messages into the receiver.
    for hostname in argv:
        print('Starting on', hostname)
        host = Host()
        host.name = hostname

        if host.name == 'localhost':
            host.context = router.local()
        else:
            host.context = router.ssh(hostname=host.name)

        # A receiver wires up a handle (via Router.add_handler()) to an
        # internal thread-safe queue object, which can be drained through calls
        # to recv.get().
        host.recv = mitogen.core.Receiver(router)
        host.recv.host = host

        # But we don't want to receive data from just one receiver, we want to
        # receive data from many. In this case we can use a Select(). It knows
        # how to efficiently sleep while waiting for the first message sent to
        # many receivers.
        select.add(host.recv)

        # The inverse of a Receiver is a Sender. Unlike receivers, senders are
        # serializable, so we can call the .to_sender() helper method to create
        # one equivalent to our host's receiver, and pass it directly to the
        # host as a function parameter.
        sender = host.recv.to_sender()

        # Finally invoke the function in the remote target. Since child_main()
        # is an infinite loop, using .call() would block the parent, since
        # child_main() never returns. Instead use .call_async(), which returns
        # another Receiver. We also want to wait for results from it --
        # although child_main() never returns, if it crashes the exception will
        # be delivered instead.
        call_recv = host.context.call_async(child_main, sender, delay)
        call_recv.host = host

        # Adding call_recv to the select will cause mitogen.core.CallError to
        # be thrown by .get() if startup of any context fails, causing halt of
        # master_main(), and the exception to be printed.
        select.add(call_recv)
        hosts.append(host)

    # Painter just wraps up all the prehistory ncurses code and keeps it out of
    # master_main().
    painter = Painter(hosts)
    try:
        try:
            master_main(painter, router, select, delay)
        except KeyboardInterrupt:
            # Shut down gracefully when the user presses CTRL+C.
            pass
    finally:
        painter.close()
709905
def socket_worker(sock, msg_q):
    """"""
    _LOGGER.debug("Starting Socket Thread.")
    while True:
        try:
            data, addr = sock.recvfrom(1024)    # buffer size is 1024 bytes
        except OSError as err:
            _LOGGER.error(err)
        else:
            _LOGGER.debug("received message: %s from %s", data, addr)
            msg_q.put(data)
        time.sleep(0.2)
365676
def listen(self, timeout=10):
        
        self._socket.settimeout(float(timeout))
        while not self.stopped.isSet():
            try:
                data, client_address = self._socket.recvfrom(4096)
            except socket.timeout:
                continue
            try:
                #Start a new thread not to block other requests
                args = ((data, client_address), )
                t = threading.Thread(target=self.receive_datagram, args=args)
                t.daemon = True
                t.start()
            except RuntimeError:
                logging.exception("Exception with Executor")
        logging.debug("closing socket")
        self._socket.close()
701321
public void start() throws IOException{
       remote_sock.setSoTimeout(iddleTimeout);
       client_sock.setSoTimeout(iddleTimeout);

       log("Starting UDP relay server on "+relayIP+":"+relayPort);
       log("Remote socket "+remote_sock.getLocalAddress()+":"+
                            remote_sock.getLocalPort());

       pipe_thread1 = new Thread(this,"pipe1");
       pipe_thread2 = new Thread(this,"pipe2");

       lastReadTime = System.currentTimeMillis();

       pipe_thread1.start();
       pipe_thread2.start();
    }
539989
@Override
	public void run() {
		stopped = false;
		try {
			try {
				serverSocket = new ServerSocket(port);
				serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5 seconds
			} finally {
				// Notify when server socket has been created
				startupBarrier.countDown();
			}

			// Server: loop until stopped
			while (!isStopped()) {
				// get a semaphore so we can ensure below that no thread is still doing stuff when we want to close the server
				if (!semaphore.tryAcquire()) {
					throw new IllegalStateException("Could not get semaphore, number of possible threads is too low.");
				}

				try {
					// Start server socket and listen for client connections
					final Socket socket;
					try {
						socket = serverSocket.accept();
					} catch (@SuppressWarnings("unused") Exception e) {
						continue; // Non-blocking socket timeout occurred: try accept() again
					}

					// Get the input and output streams
					BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));         // NOSONAR - test class works only locally anyway
					PrintWriter out = new PrintWriter(socket.getOutputStream());       // NOSONAR - test class works only locally anyway

					synchronized (this) {
						/*
						 * We synchronize over the handle method and the list update because the client call completes inside
						 * the handle method and we have to prevent the client from reading the list until we've updated it.
						 * For higher concurrency, we could just change handle to return void and update the list inside the
						 * method
						 * to limit the duration that we hold the lock.
						 */
						List<SmtpMessage> messages = handleTransaction(out, input);
						receivedMail.addAll(messages);
					}
					socket.close();
				} finally {
					semaphore.release();
				}
			}
		} catch (Exception e) {
			// TODO: Should throw an appropriate exception here
			log.log(Level.SEVERE, "Caught exception: ", e);
		} finally {
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					log.log(Level.SEVERE, "Caught exception: ", e);
				}
			}
		}
	}
294111
def _reader_thread_proc(self, timeout):
    """"""
    for data in self.stream.read_until_close(timeout_ms=timeout):
      if self.stdout is not None:
        self.stdout.write(data)
941480
def wait(self, seconds=None, **kw):
        ''
        # Use ping/pong to unblock recv for polling transport
        self._heartbeat_thread.hurry()
        # Use timeout to unblock recv for websocket transport
        self._transport.set_timeout(seconds=1)
        # Listen
        warning_screen = self._yield_warning_screen(seconds)
        for elapsed_time in warning_screen:
            if self._should_stop_waiting(**kw):
                break
            try:
                try:
                    self._process_packets()
                except TimeoutError:
                    pass
                except KeyboardInterrupt:
                    self._close()
                    raise
            except ConnectionError as e:
                self._opened = False
                try:
                    warning = Exception('[connection error] %s' % e)
                    warning_screen.throw(warning)
                except StopIteration:
                    self._warn(warning)
                try:
                    namespace = self.get_namespace()
                    namespace._find_packet_callback('disconnect')()
                except PacketError:
                    pass
        self._heartbeat_thread.relax()
        self._transport.set_timeout()
1013814
def main(self):
        
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.bind((self.host, self.port))
            self.sock.listen(5)
            self.sock.settimeout(END_RESP)
            
            self.stop = self.terminate = False
            
            while not (self.stop or self.terminate):
                try:
                    conn, addr = self.sock.accept()
                except socket.error:
                    # We have timed out, hurry and get back to accept those 
                    # connections!
                    pass
                except KeyboardInterrupt:
                    # We've been told to quit, do so!
                    self.terminate_server()
                else:
                    threaded(self._handler, (conn,))
            
            while not self.terminate:
                time.sleep(END_RESP)
            # We are done, the finally will close the socket.
        finally:
            self.sock.close()
480726
@SuppressWarnings("resource")
  public void run() {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY-1);
    DatagramChannel sock = H2O._udpSocket, errsock = null;
    boolean saw_error = false;

    while( true ) {
      try {
        // Cleanup from any prior socket failures.  Rare unless we're really sick.
        if( errsock != null ) { // One time attempt a socket close
          final DatagramChannel tmp2 = errsock; errsock = null;
          tmp2.close();       // Could throw, but errsock cleared for next pass
        }
        if( saw_error ) Thread.sleep(1000); // prevent deny-of-service endless socket-creates
        saw_error = false;

        // ---
        // Common-case setup of a socket
        if( sock == null ) {
          sock = DatagramChannel.open();
          sock.socket().bind(H2O.SELF._key);
        }

        // Receive a packet & handle it
        basic_packet_handling(new AutoBuffer(sock));

      } catch( java.nio.channels.AsynchronousCloseException ex ) {
        break;                  // Socket closed for shutdown
      } catch( java.nio.channels.ClosedChannelException ex ) {
        break;                  // Socket closed for shutdown
      } catch( Exception e ) {
        // On any error from anybody, close all sockets & re-open
        Log.err("UDP Receiver error on port "+H2O.H2O_PORT,e);
        saw_error = true;
        errsock  = sock ;  sock  = null; // Signal error recovery on the next loop
      }
    }
  }
592244
public void run(){
       try{
          if(Thread.currentThread().getName().equals("pipe1"))
             pipe(remote_sock,client_sock,false);
          else
             pipe(client_sock,remote_sock,true);
       }catch(IOException ioe){
       }finally{
          abort();
          log("UDP Pipe thread "+Thread.currentThread().getName()+" stopped.");
       }

    }
513417
def mainloop(self):
        """"""
        try:
            while (not self.ev_quit.is_set()):
                try:
                    self.handle_request()

                except socketTimeout:
                    continue
        finally:
            self.socket.close()
909468
def run(self):
    """"""
    self._live = True
    self._sock.settimeout(self.LISTEN_TIMEOUT_S)

    # Passing in INADDR_ANY means the kernel will choose the default interface.
    # The localhost address is used to receive messages sent in "local_only"
    # mode and the default address is used to receive all other messages.
    for interface_ip in (socket.INADDR_ANY, LOCALHOST_ADDRESS):
      self._sock.setsockopt(
          socket.IPPROTO_IP,
          socket.IP_ADD_MEMBERSHIP,
          # IP_ADD_MEMBERSHIP takes the 8-byte group address followed by the IP
          # assigned to the interface on which to listen.
          struct.pack('!4sL', socket.inet_aton(self.address), interface_ip))

    if sys.platform == 'darwin':
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEPORT,
                            1)  # Allow multiple listeners to bind.
    else:
      self._sock.setsockopt(socket.SOL_SOCKET,
                            socket.SO_REUSEADDR,
                            1)  # Allow multiple listeners to bind.
    self._sock.bind((self.address, self.port))

    while self._live:
      try:
        data, address = self._sock.recvfrom(MAX_MESSAGE_BYTES)
        data = data.decode('utf-8')
        log_line = 'Received multicast message from %s: %s' % (address, data)
        response = self._callback(data)
        if response is not None:
          log_line += ', responding with %s bytes' % len(response)
          # Send replies out-of-band instead of with the same multicast socket
          # so that multiple processes on the same host can listen for
          # requests and reply (if they all try to use the multicast socket
          # to reply, they conflict and this sendto fails).
          response = response.encode('utf-8')
          socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(
              response, address)
        _LOG.debug(log_line)
      except socket.timeout:
        pass
      except socket.error:
        _LOG.debug('Error receiving multicast message', exc_info=True)