Create a new socket, taking into account
things like retry attempts and delays.

\return
This method does not return any value.
506091
protected function createSocket()
    {
        $now = $this->getCurrentTime();
        if ($this->retryTime === null) {
            $attempt = true;
        } else {
            $attempt = ($now >= $this->retryTime);
        }

        if (!$attempt) {
            return;
        }

        $this->socket = $this->makeSocket();
        if ($this->socket !== false) {
            $this->retryTime = null;
            return;
        }

        if ($this->retryTime === null) {
            $this->retryPeriod = $this->retryStart;
        } else {
            $this->retryPeriod *= $this->retryFactor;
            if ($this->retryPeriod > $this->retryMax) {
                $this->retryPeriod = $this->retryMax;
            }
        }
        $this->retryTime = $now + $this->retryPeriod;
    }
867769
def initialize_socket(uri, opts = {})
      return if opts[:socket]

      @socket = TCPSocket.new(uri.host, uri.port)
      opts.merge!({:socket => @socket})
      @intentional_termination = false
    end
690693
def _create_server(host, port):
    

    exc = socket.error("getaddrinfo returns an empty list")
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            # Create the listening socket
            sock = socket.socket(af, socktype, proto)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(sa)
            sock.listen(1024)
            return sock

        except socket.error as exc:
            # Clean up after ourselves
            if sock is not None:
                sock.close()

    # Couldn't create a listening socket
    raise exc
511992
def get_socket(host, port, timeout=None):
    
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socket(af, socktype, proto)
            if timeout is not None:
                sock.settimeout(timeout)
            sock.connect(sa)
            return sock

        except error:
            if sock is not None:
                sock.close()

    raise error
698408
function(socket, options) {
    if(!options) {
        options = socket || {};
        socket = new net.Socket(options);
    }

    this.socket = socket;
    this.connected = options.connected || socket.writable && socket.readable || false;

    this.retry = {
        retries: 0,
        max: options.maxRetries || 10,
        interval: options.retryInterval || 5000,
        wait: options.retryInterval || 5000
    };

    this.$reconnect = options.reconnect || false;
    this.$options = options;

    this.$buff = null;
    this.$msg = null;

    EventEmitter.call(this, {
        delimiter: "::",
        wildcard: true,
        maxListeners: options.maxListeners || 10
    });

    this._setup();
}
68943
def _get_socketpair(self):
        
        try:
            return self._cls_idle_socketpairs.pop()  # pop() must be atomic
        except IndexError:
            rsock, wsock = socket.socketpair()
            set_cloexec(rsock.fileno())
            set_cloexec(wsock.fileno())
            self._cls_all_sockets.extend((rsock, wsock))
            return rsock, wsock
11503
protected function makeSocket(): void
    {
        if ($this->useSSL) {
            if (!file_exists($this->cert)) {
                throw new \Exception('Cert file not found');
            }

            $context = stream_context_create([
                'ssl' => [
                    'local_cert'        => $this->cert,
                    'passphrase'        => $this->passPhrase,
                    'verify_peer'       => false,
                    'verify_peer_name'  => false,
                    'allow_self_signed' => true,
                    'verify_depth'      => 0
                ]
            ]);

            $protocol = 'ssl';
        } else {
            $context = stream_context_create();
            $protocol = 'tcp';
        }

        $this->socket = stream_socket_server("$protocol://{$this->host}:{$this->port}", $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);

        if ($this->useConnector) {
            if (file_exists(static::$connector)) {
                unlink(static::$connector);
            }

            $this->unixConnector = stream_socket_server('unix://' . static::$connector, $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
            chmod(static::$connector, 0777);
        }

        if (!$this->socket) {
            throw new SocketException($errorString, $errorNumber);
        }
    }
644872
private Socket nextSocket() {
    Socket result;
    synchronized (lock) {
      result = nextSocket;
      while (!done && result == null) {
        try {
          lock.wait();
        } catch (InterruptedException e) {
          done = true;
        }
        result = nextSocket;
      }
      nextSocket = null;
    }

    if (result != null) {
      // Java InputStream API is blocking by default with no reliable way to stop pending
      // read() call. Setting the timeout to underlying socket will make socket's underlying
      // read() calls throw SocketTimeoutException which unblocks read(). The exception must
      // be properly handled by calling code.
      try {
        // TODO(buck_team): this does not work with current NGUnixDomainSocket
        // implementation
        result.setSoTimeout(this.heartbeatTimeoutMillis);
      } catch (SocketException e) {
        // this exception might be thrown if socket is already closed
        // so we just return null
        return null;
      }
    }

    return result;
  }
743834
def connected_socket(address, timeout=3):
    
    sock = socket.create_connection(address, timeout)
    yield sock
    sock.close()
1118796
def _create_connection(self):
        
        transport = SSL if self.ssl else TCP
        return transport(self.server, self.port)
599607
def _register_socket(self):
        """"""
        _socket = socket.socket(*Socket.protocols[self.connection.proto])
        _socket.settimeout(self.timeout)

        # Reconfigure original socket options.
        if self.connection.sockopts:
            for sock_opt in self.connection.sockopts:
                level, option, value = sock_opt
                _socket.setsockopt(level, option, value)

        _socket.connect(self.connection.connect_to)
        return _socket
743486
def socket(self, socket_type, identity=None, mechanism=None):
        
        socket = Socket(
            context=self,
            socket_type=socket_type,
            identity=identity,
            mechanism=mechanism,
            loop=self.loop,
        )
        self.register_child(socket)
        return socket
1285382
private ServerSocket createServerSocket(int port) throws IOException {
    try {
      ServerSocket sock = new ServerSocket();
      // Prevent 2MSL delay problem on server restarts
      sock.setReuseAddress(true);
      // Bind to listening port
      if (port == 0) {
        sock.bind(null);
        serverPort = sock.getLocalPort();
      } else {
        sock.bind(new InetSocketAddress(port));
      }
      return sock;
    } catch (IOException ioe) {
      throw new IOException("Could not create ServerSocket on port " + port + "." +
                            ioe);
    }
  }
53354
def init
      return if @has_been_init

      @socket = init_socket(@socket)
      @socket.connect # costly and blocking !

      internalWrapper = (Struct.new :url, :socket do
        def write(*args)
          self.socket.write(*args)
        end
      end).new @url.to_s, @socket

      # this, also, is costly and blocking
      @driver = WebSocket::Driver.client internalWrapper
      @driver.on :open do
        @connected = true
        unless @callbacks[:open].nil?
          @callbacks[:open].call
        end
      end

      @driver.on :error do |event|
        @connected = false
        unless @callbacks[:error].nil?
          @callbacks[:error].call
        end
      end

      @driver.on :message do |event|
        data = JSON.parse event.data
        unless @callbacks[:message].nil?
          @callbacks[:message].call data
        end
      end
      @driver.start
      @has_been_init = true
    end
1103360
def ():
    """"""

    # create a socket for recording layer 2, 3 and 4 frames
    s = None
    try:
        log.info("Creating l234 socket")
        s = socket.socket(socket.AF_PACKET,
                          socket.SOCK_RAW,
                          socket.ntohs(0x0003))
    except socket.error as msg:
        log.error(("Socket could not be created ex={}")
                  .format(msg))
    return s
1177017
def _new_conn(self):
        
        extra_kw = {}
        if self.source_address:
            extra_kw['source_address'] = self.source_address

        if self.socket_options:
            extra_kw['socket_options'] = self.socket_options

        try:
            conn = connection.create_connection(
                (self._dns_host, self.port), self.timeout, **extra_kw)

        except SocketTimeout as e:
            raise ConnectTimeoutError(
                self, "Connection to %s timed out. (connect timeout=%s)" %
                (self.host, self.timeout))

        except SocketError as e:
            raise NewConnectionError(
                self, "Failed to establish a new connection: %s" % e)

        return conn
1157908
private function createResponse(Request $request, Socket $socket): \Generator
    {
        try {
            assert(yield from $this->log->log(
                Log::DEBUG,
                'Received request from %s:%d for %s',
                $socket->getRemoteAddress(),
                $socket->getRemotePort(),
                $request->getUri()
            ));

            $response = $this->handler->onRequest($request, $socket);

            if ($response instanceof \Generator) {
                $response = yield from $response;
            } elseif ($response instanceof Awaitable) {
                $response = yield $response;
            }

            if (!$response instanceof Response) {
                throw new InvalidResultError(sprintf(
                    'A %s object was not returned from %::onRequest().',
                    Response::class,
                    get_class($this->handler)
                ), $response);
            }
        } catch (Throwable $exception) {
            yield from $this->log->log(
                Log::ERROR,
                "Uncaught exception when creating response to a request from %s:%d on %s:%d in file %s on line %d: %s",
                $socket->getRemoteAddress(),
                $socket->getRemotePort(),
                $socket->getLocalAddress(),
                $socket->getLocalPort(),
                $exception->getFile(),
                $exception->getLine(),
                $exception->getMessage()
            );
            $response = yield from $this->createDefaultErrorResponse(500);
        }

        return $response;
    }