Connect the transport

@param timeout
@return whether the transport was connected
@throws TransportException
435683
public synchronized boolean connect ( long timeout ) throws TransportException {
        int st = this.state;
        try {
            switch ( st ) {
            case 0:
                break;
            case 1:
                // already connecting
                this.thread.wait(timeout); /* wait for doConnect */
                st = this.state;
                switch ( st ) {
                case 1: /* doConnect never returned */
                    this.state = 6;
                    cleanupThread(timeout);
                    throw new ConnectionTimeoutException("Connection timeout");
                case 2:
                    if ( this.te != null ) { /* doConnect throw Exception */
                        this.state = 4; /* error */
                        cleanupThread(timeout);
                        throw this.te;
                    }
                    this.state = 3; /* Success! */
                    return true;
                }
                break;
            case 3:
                return true; // already connected
            case 4:
                this.state = 6;
                throw new TransportException("Connection in error", this.te);
            case 5:
            case 6:
                log.debug("Trying to connect a disconnected transport");
                return false;
            default:
                TransportException tex = new TransportException("Invalid state: " + st);
                throw tex;
            }

            if ( log.isDebugEnabled() ) {
                log.debug("Connecting " + this.name);
            }

            this.state = 1;
            this.te = null;

            Thread t = new Thread(this, this.name);
            t.setDaemon(true);
            this.thread = t;

            synchronized ( this.thread ) {
                t.start();
                t.wait(timeout); /* wait for doConnect */

                st = this.state;
                switch ( st ) {
                case 1: /* doConnect never returned */
                    this.state = 6;
                    throw new ConnectionTimeoutException("Connection timeout");
                case 2:
                    if ( this.te != null ) { /* doConnect throw Exception */
                        this.state = 4; /* error */
                        throw this.te;
                    }
                    this.state = 3; /* Success! */
                    return true;
                case 3:
                    return true;
                default:
                    return false;
                }
            }
        }
        catch ( ConnectionTimeoutException e ) {
            cleanupThread(timeout);
            // allow to retry the connection
            this.state = 0;
            throw e;
        }
        catch ( InterruptedException ie ) {
            this.state = 6;
            cleanupThread(timeout);
            throw new TransportException(ie);
        }
        catch ( TransportException e ) {
            cleanupThread(timeout);
            throw e;
        }
        finally {
            /*
             * This guarantees that we leave in a valid state
             */
            st = this.state;
            if ( st != 0 && st != 3 && st != 4 && st != 5 && st != 6 ) {
                log.error("Invalid state: " + st);
                this.state = 6;
                cleanupThread(timeout);
            }
        }
    }
615785
def connect_nonblock( addr, timeout )
      sockaddr = ::Socket.pack_sockaddr_in(addr[1], addr[3])
      sock     = blank_socket()
      sock.connect_nonblock( sockaddr )
      return sock
    rescue Errno::EINPROGRESS
      if !wait_writable(timeout, sock)
        raise Timeout, "Could not connect to #{host}:#{port} within #{timeout} seconds"
      end
      return connect_nonblock_finalize( sock, sockaddr )
    rescue => ex
      raise Error, "Could not connect to #{host}:#{port}: #{ex.class}: #{ex.message}", ex.backtrace
    end
1345322
public void reconnect (int timeout) throws IOException {
		if (connectHost == null) throw new IllegalStateException("This client has never been connected.");
		connect(timeout, connectHost, connectTcpPort, connectUdpPort);
	}
1238826
def check_port(port, host, timeout=10):
    
    logger.info("trying to open connection to %s:%s", host, port)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.settimeout(timeout)
        result = sock.connect_ex((host, port))
        logger.info("was connection successful? errno: %s", result)
        if result == 0:
            logger.debug('port is opened: %s:%s' % (host, port))
            return True
        else:
            logger.debug('port is closed: %s:%s' % (host, port))
            return False
    finally:
        sock.close()
988862
def connection_made(self, transport):
        """"""
        self.logger.info('Connection made at object %s', id(self))
        self.transport = transport
        self.keepalive = True

        if self._timeout:
            self.logger.debug('Registering timeout event')
            self._timout_handle = self._loop.call_later(
                self._timeout, self._handle_timeout)
414306
public function connect($timeout = 5.0)
    {
        if (true === $this->isConnected()) {
            return false;
        }

        $errorNumber = 0;
        $errorMessage = '';

        $this->connection = @fsockopen(
            $this->parameters['host'],
            $this->parameters['port'],
            $errorNumber,
            $errorMessage,
            $timeout
        );

        if (false === $this->isConnected()) {
            throw new GearmanConnectionException($errorMessage, $errorNumber);
        }

        return true;
    }
823506
public boolean requestTime(String host, int timeout) {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            socket.setSoTimeout(timeout);
            InetAddress address = InetAddress.getByName(host);
            byte[] buffer = new byte[NTP_PACKET_SIZE];
            DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);

            // set mode = 3 (client) and version = 3
            // mode is in low 3 bits of first byte
            // version is in bits 3-5 of first byte
            buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);

            // get current time and write it to the request packet
            long requestTime = System.currentTimeMillis();
            long requestTicks = SystemClock.elapsedRealtime();
            writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);

            socket.send(request);

            // read the response
            DatagramPacket response = new DatagramPacket(buffer, buffer.length);
            socket.receive(response);
            long responseTicks = SystemClock.elapsedRealtime();
            long responseTime = requestTime + (responseTicks - requestTicks);

            // extract the results
            long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
            long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
            long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
            long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
            // receiveTime = originateTime + transit + skew
            // responseTime = transmitTime + transit - skew
            // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
            //             = ((originateTime + transit + skew - originateTime) +
            //                (transmitTime - (transmitTime + transit - skew)))/2
            //             = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
            //             = (transit + skew - transit + skew)/2
            //             = (2 * skew)/2 = skew
            mClockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;
            // if (false) Log.d(TAG, "round trip: " + roundTripTime + " ms");
            // if (false) Log.d(TAG, "clock offset: " + clockOffset + " ms");

            // save our results - use the times on this side of the network latency
            // (response rather than request time)
            mNtpTime = responseTime + mClockOffset;
            mNtpTimeReference = responseTicks;
            mRoundTripTime = roundTripTime;
        } catch (Exception e) {
            return false;
        } finally {
            if (socket != null) {
                socket.close();
            }
        }

        return true;
    }
863428
private Connection<CL> waitForConnection(int timeout) throws ConnectionException {
        Connection<CL> connection = null;
        long startTime = System.currentTimeMillis();
        try {
            blockedThreads.incrementAndGet();
            connection = availableConnections.poll(timeout, TimeUnit.MILLISECONDS);
            if (connection != null)
                return connection;
            
            throw new PoolTimeoutException("Timed out waiting for connection")
                .setHost(getHost())
                .setLatency(System.currentTimeMillis() - startTime);
        }
        catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new InterruptedOperationException("Thread interrupted waiting for connection")
                .setHost(getHost())
                .setLatency(System.currentTimeMillis() - startTime);
        }
        finally {
            blockedThreads.decrementAndGet();
        }
    }
494360
private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout,
      int pingIntervalMillis, boolean connectionRetryEnabled) throws IOException {
    boolean foundPooledConnection = false;
    RealConnection result = null;
    Route selectedRoute = null;
    RealConnection releasedConnection;
    Socket toClose;
    synchronized (connectionPool) {
      if (transmitter.isCanceled()) throw new IOException("Canceled");
      hasStreamFailure = false; // This is a fresh attempt.

      Route previousRoute = retryCurrentRoute()
          ? transmitter.connection.route()
          : null;

      // Attempt to use an already-allocated connection. We need to be careful here because our
      // already-allocated connection may have been restricted from creating new exchanges.
      releasedConnection = transmitter.connection;
      toClose = transmitter.connection != null && transmitter.connection.noNewExchanges
          ? transmitter.releaseConnectionNoEvents()
          : null;

      if (transmitter.connection != null) {
        // We had an already-allocated connection and it's good.
        result = transmitter.connection;
        releasedConnection = null;
      }

      if (result == null) {
        // Attempt to get a connection from the pool.
        if (connectionPool.transmitterAcquirePooledConnection(address, transmitter, null, false)) {
          foundPooledConnection = true;
          result = transmitter.connection;
        } else {
          selectedRoute = previousRoute;
        }
      }
    }
    closeQuietly(toClose);

    if (releasedConnection != null) {
      eventListener.connectionReleased(call, releasedConnection);
    }
    if (foundPooledConnection) {
      eventListener.connectionAcquired(call, result);
    }
    if (result != null) {
      // If we found an already-allocated or pooled connection, we're done.
      return result;
    }

    // If we need a route selection, make one. This is a blocking operation.
    boolean newRouteSelection = false;
    if (selectedRoute == null && (routeSelection == null || !routeSelection.hasNext())) {
      newRouteSelection = true;
      routeSelection = routeSelector.next();
    }

    List<Route> routes = null;
    synchronized (connectionPool) {
      if (transmitter.isCanceled()) throw new IOException("Canceled");

      if (newRouteSelection) {
        // Now that we have a set of IP addresses, make another attempt at getting a connection from
        // the pool. This could match due to connection coalescing.
        routes = routeSelection.getAll();
        if (connectionPool.transmitterAcquirePooledConnection(
            address, transmitter, routes, false)) {
          foundPooledConnection = true;
          result = transmitter.connection;
        }
      }

      if (!foundPooledConnection) {
        if (selectedRoute == null) {
          selectedRoute = routeSelection.next();
        }

        // Create a connection and assign it to this allocation immediately. This makes it possible
        // for an asynchronous cancel() to interrupt the handshake we're about to do.
        result = new RealConnection(connectionPool, selectedRoute);
        connectingConnection = result;
      }
    }

    // If we found a pooled connection on the 2nd time around, we're done.
    if (foundPooledConnection) {
      eventListener.connectionAcquired(call, result);
      return result;
    }

    // Do TCP + TLS handshakes. This is a blocking operation.
    result.connect(connectTimeout, readTimeout, writeTimeout, pingIntervalMillis,
        connectionRetryEnabled, call, eventListener);
    connectionPool.getRouteDatabase().connected(result.route());

    Socket socket = null;
    synchronized (connectionPool) {
      connectingConnection = null;
      // Last attempt at connection coalescing, which only occurs if we attempted multiple
      // concurrent connections to the same host.
      if (connectionPool.transmitterAcquirePooledConnection(address, transmitter, routes, true)) {
        // We lost the race! Close the connection we created and return the pooled connection.
        result.noNewExchanges = true;
        socket = result.socket();
        result = transmitter.connection;
      } else {
        connectionPool.put(result);
        transmitter.acquireConnectionNoEvents(result);
      }
    }
    closeQuietly(socket);

    eventListener.connectionAcquired(call, result);
    return result;
  }
165469
async def connect(self, timeout=None, ssl=None):
        
        await self._connect(timeout=timeout, ssl=ssl)
        self._connected = True

        self._send_task = self._loop.create_task(self._send_loop())
        self._recv_task = self._loop.create_task(self._recv_loop())
707026
def connect_pull(self, timeout=1):
        '''
        
        '''
        if self.cpush:
            return True

        if self._run_io_loop_sync:
            with salt.utils.asynchronous.current_ioloop(self.io_loop):
                if self.pusher is None:
                    self.pusher = salt.transport.ipc.IPCMessageClient(
                        self.pulluri,
                        io_loop=self.io_loop
                    )
                try:
                    self.io_loop.run_sync(
                        lambda: self.pusher.connect(timeout=timeout))
                    self.cpush = True
                except Exception:
                    pass
        else:
            if self.pusher is None:
                self.pusher = salt.transport.ipc.IPCMessageClient(
                    self.pulluri,
                    io_loop=self.io_loop
                )
            # For the asynchronous case, the connect will be deferred to when
            # fire_event() is invoked.
            self.cpush = True
        return self.cpush
699900
public void processTimeout(final TimeoutEvent timeoutEvent) {
		Transaction eventTransaction = null;
		if(timeoutEvent.isServerTransaction()) {
			eventTransaction = timeoutEvent.getServerTransaction();
		} else {
			eventTransaction = timeoutEvent.getClientTransaction();
		}
		final Transaction transaction = eventTransaction;
		if(logger.isDebugEnabled()) {
			logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString());
		}

		final TransactionApplicationData tad = (TransactionApplicationData) transaction.getApplicationData();
		if(tad != null && tad.getSipServletMessage() != null) {
			// https://github.com/RestComm/sip-servlets/issues/107 guard against NPEon concurrent cleanup
			final SipServletMessageImpl sipServletMessage = tad.getSipServletMessage();
			final MobicentsSipSessionKey sipSessionKey = sipServletMessage.getSipSessionKey();
			final MobicentsSipSession sipSession = sipServletMessage.getSipSession();
			getAsynchronousExecutor().execute(new Runnable() {
				public void run() {
					try {
						if(logger.isDebugEnabled()) {
							logger.debug("transaction " + transaction + " timed out => " + transaction.getRequest().toString());
						}
						boolean appNotifiedOfPrackNotReceived = false;
						// session can be null if a message was sent outside of the container by the container itself during Initial request dispatching
						// but the external host doesn't send any response so we call out to the application only if the session is not null
						if(logger.isDebugEnabled()) {
                            logger.debug("time out happened on sipSession " + sipSession);
                        }
						if(sipSession != null) {
							SipContext sipContext = findSipApplication(sipSessionKey.getApplicationName());
							//the context can be null if the server is being shutdown
							if(sipContext != null) {
								MobicentsSipApplicationSession sipApplicationSession = sipSession.getSipApplicationSession();
								try {
									sipContext.enterSipApp(sipApplicationSession, sipSession, false, true);
									MobicentsB2BUAHelper b2buaHelperImpl = sipSession.getB2buaHelper();

									if(b2buaHelperImpl != null && tad.getSipServletMessage() instanceof SipServletRequestImpl) {
										b2buaHelperImpl.unlinkRequestInternal((SipServletRequestImpl)tad.getSipServletMessage(), false);
									}
									// naoki : Fix for Issue 1618 http://code.google.com/p/mobicents/issues/detail?id=1618 on Timeout don't do the 408 processing for Server Transactions
									if(logger.isDebugEnabled()) {
			                            logger.debug("time out happened on server tx ? " + timeoutEvent.isServerTransaction() + " and message " + sipServletMessage);
			                        }
									if(sipServletMessage instanceof SipServletRequestImpl && !timeoutEvent.isServerTransaction()) {
										try {
											ProxyBranchImpl proxyBranchImpl = tad.getProxyBranch();
											if(proxyBranchImpl != null) {
												ProxyImpl proxy = (ProxyImpl) proxyBranchImpl.getProxy();
												if(proxy.getFinalBranchForSubsequentRequests() != null) {
													tad.cleanUp();
													transaction.setApplicationData(null);
													return;
												}
											}
											SipServletRequestImpl sipServletRequestImpl = (SipServletRequestImpl) sipServletMessage;
											if(sipServletRequestImpl.visitNextHop()) {
												return;
											}
											sipServletMessage.setTransaction(transaction);
											SipServletResponseImpl response = (SipServletResponseImpl) sipServletRequestImpl.createResponse(408, null, false, true);
											// Fix for Issue 1734
											sipServletRequestImpl.setResponse(response);
											MessageDispatcher.callServlet(response);
											if(tad.getProxyBranch() != null) {
												tad.getProxyBranch().setResponse(response);
												tad.getProxyBranch().onResponse(response, response.getStatus());
											}
											sipSession.updateStateOnResponse(response, true);
										} catch (Throwable t) {
											logger.error("Failed to deliver 408 response on transaction timeout" + transaction, t);
										}
									}
									// Guard only invite tx should check that, otherwise proxy might become null http://code.google.com/p/mobicents/issues/detail?id=2350
									// Should check only Server Tx for ack or prack not received http://code.google.com/p/mobicents/issues/detail?id=2525
									if(Request.INVITE.equals(sipServletMessage.getMethod()) && timeoutEvent.isServerTransaction()) {
										checkForAckNotReceived(sipServletMessage);
										appNotifiedOfPrackNotReceived = checkForPrackNotReceived(sipServletMessage);
									}
								} finally {
									sipSession.removeOngoingTransaction(transaction);
									sipSession.setRequestsPending(0);
									sipContext.exitSipApp(sipApplicationSession, sipSession);
								}
								// don't invalidate here because if the application sends a final response on the noPrack received
								// the ACK to this final response won't be able to get routed since the sip session would have been invalidated
								if(!appNotifiedOfPrackNotReceived) {
									tryToInvalidateSession(sipSessionKey, false);
								}
							}
						}
						// don't clean up for the same reason we don't invalidate the sip session right above
						tad.cleanUp();
						transaction.setApplicationData(null);
					} catch (Exception e) {
						logger.error("Problem handling timeout", e);
					}
				}
			});
		}
	}
988013
public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) {
        assertNumericArgument(timeout, true);
        this.requestTimeout = unit.toMillis(timeout);
        return this;
    }
909836
public synchronized Operation timeout(@Nullable final Long timeout) {
        this.timeout = timeout == null || timeout > 0 ? timeout : null;
        return this;
    }
592637
public void setResponseTimeout(int timeout) {
        try {
            getConnection().setReadTimeout(timeout);
        } catch (Exception e) {
            Modbus.log().warning(e.getLocalizedMessage());
        }
    }
1273429
public void setTimeout(int timeout) {
    this.timeout = timeout;
    try {
      socket.setSoTimeout(timeout);
    } catch (SocketException sx) {
      LOGGER.warn("Could not set socket timeout.", sx);
    }
  }
355720
def _connect(self, timeout=None):
        '''
        
        '''
        if isinstance(self.socket_path, int):
            sock_type = socket.AF_INET
            sock_addr = ('127.0.0.1', self.socket_path)
        else:
            sock_type = socket.AF_UNIX
            sock_addr = self.socket_path

        self.stream = None
        if timeout is not None:
            timeout_at = time.time() + timeout

        while True:
            if self._closing:
                break

            if self.stream is None:
                with salt.utils.asynchronous.current_ioloop(self.io_loop):
                    self.stream = IOStream(
                        socket.socket(sock_type, socket.SOCK_STREAM),
                    )

            try:
                log.trace('IPCClient: Connecting to socket: %s', self.socket_path)
                yield self.stream.connect(sock_addr)
                self._connecting_future.set_result(True)
                break
            except Exception as e:
                if self.stream.closed():
                    self.stream = None

                if timeout is None or time.time() > timeout_at:
                    if self.stream is not None:
                        self.stream.close()
                        self.stream = None
                    self._connecting_future.set_exception(e)
                    break

                yield tornado.gen.sleep(1)