Create a new EISCP::Receiver object to communicate with a receiver.
 If no host is given, use auto discovery and create a
 receiver object using the first host to respond.

 Manages the thread and uses the same block passed to through #connect.
554435
def update_thread
      # Kill thread if it exists
      thread && @thread.kill
      @thread = Thread.new do
        loop do
          message = recv
          @state[message.command] = message.value
          yield(message) if block_given?
        end
      end
    end
460640
async def _connect(self, hostname, port, reconnect=False, channels=[],
                       encoding=protocol.DEFAULT_ENCODING, source_address=None):
        
        # Create connection if we can't reuse it.
        if not reconnect or not self.connection:
            self._autojoin_channels = channels
            self.connection = connection.Connection(hostname, port, source_address=source_address,
                                                    eventloop=self.eventloop)
            self.encoding = encoding

        # Connect.
        await self.connection.connect()
678015
def execute(receiver, method, args, block)
      @mutex.synchronize do
        raise "already calling" if @call
        @call = Call::Sync.new(self, method, args, block)
      end

      receiver << @call
    end
115252
def receive(timeout = nil, &block)
      loop do
        message = @receivers.receive(timeout, &block)
        return message unless message.is_a?(SystemEvent)

        handle_system_event(message)
      end
    end
852707
def work_on_machine(context):
    
    print("Created context. Context ID is", context.context_id)

    # You don't need to understand any/all of this, but it's helpful to grok
    # the whole chain:

    # - Context.call() is a light wrapper around .call_async(), the wrapper
    #   simply blocks the caller until a reply arrives.
    # - .call_async() serializes the call signature into a message and passes
    #   it to .send_async()
    # - .send_async() creates a mitogen.core.Receiver() on the local router.
    #   The receiver constructor uses Router.add_handle() to allocate a
    #   'reply_to' handle and install a callback function that wakes the
    #   receiver when a reply message arrives.
    # - .send_async() puts the reply handle in Message.reply_to field and
    #   passes it to .send()
    # - Context.send() stamps the destination context ID into the
    #   Message.dst_id field and passes it to Router.route()
    # - Router.route() uses Broker.defer() to schedule _async_route(msg)
    #   on the Broker thread.
    # [broker thread]
    # - The broker thread wakes and calls _async_route(msg)
    # - Router._async_route() notices 'dst_id' is for a remote context and
    #   looks up the stream on which messages for dst_id should be sent (may be
    #   direct connection or not), and calls Stream.send()
    # - Stream.send() packs the message into a bytestring, appends it to
    #   Stream._output_buf, and calls Broker.start_transmit()
    # - Broker finishes work, reenters IO loop. IO loop wakes due to writeable
    #   stream.
    # - Stream.on_transmit() writes the full/partial buffer to SSH, calls
    #   stop_transmit() to mark the stream unwriteable once _output_buf is
    #   empty.
    # - Broker IO loop sleeps, no readers/writers.
    # - Broker wakes due to SSH stream readable.
    # - Stream.on_receive() called, reads the reply message, converts it to a
    #   Message and passes it to Router._async_route().
    # - Router._async_route() notices message is for local context, looks up
    #   target handle in the .add_handle() registry.
    # - Receiver._on_receive() called, appends message to receiver queue.
    # [main thread]
    # - Receiver.get() used to block the original Context.call() wakes and pops
    #   the message from the queue.
    # - Message data (pickled return value) is deserialized and returned to the
    #   caller.
    print("It's running on the local machine. Its PID is",
          context.call(os.getpid))

    # Now let's call a function defined in this module. On receiving the
    # function call request, the child attempts to import __main__, which is
    # initially missing, causing the importer in the child to request it from
    # its parent. That causes _this script_ to be sent as the module source
    # over the wire.
    print("Calling md5sum(/etc/passwd) in the child:",
          context.call(md5sum, '/etc/passwd'))

    # Now let's "transfer" a file. The simplest way to do this is calling a
    # function that returns the file data, which is totally fine for small
    # files.
    print("Download /etc/passwd via function call: %d bytes" % (
        len(context.call(get_file_contents, '/etc/passwd'))
    ))

    # And using function calls, in the other direction:
    print("Upload /tmp/blah via function call: %s" % (
        context.call(put_file_contents, '/tmp/blah', b'blah!'),
    ))

    # Now lets transfer what might be a big files. The problem with big files
    # is that they may not fit in RAM. This uses mitogen.services.FileService
    # to implement streamy file transfer instead. The sender must have a
    # 'service pool' running that will host FileService. First let's do the
    # 'upload' direction, where the master hosts FileService.

    # Steals the 'Router' reference from the context object. In a real app the
    # pool would be constructed once at startup, this is just demo code.
    file_service = mitogen.service.FileService(context.router)

    # Start the pool.
    pool = mitogen.service.Pool(context.router, services=[file_service])

    # Grant access to a file on the local disk from unprivileged contexts.
    # .register() is also exposed as a service method -- you can call it on a
    # child context from any more privileged context.
    file_service.register('/etc/passwd')

    # Now call our wrapper function that knows how to handle the transfer. In a
    # real app, this wrapper might also set ownership/modes or do any other
    # app-specific stuff relating to the file that was transferred.
    print("Streamy upload /etc/passwd: remote result: %s" % (
        context.call(
            streamy_download_file,
            # To avoid hard-wiring streamy_download_file(), we want to pass it
            # a Context object that hosts the file service it should request
            # files from. Router.myself() returns a Context referring to this
            # process.
            context=router.myself(),
            path='/etc/passwd',
        ),
    ))

    # Shut down the pool now we're done with it, else app will hang at exit.
    # Once again, this should only happen once at app startup/exit, not for
    # every file transfer!
    pool.stop(join=True)

    # Now let's do the same thing but in reverse: we use FileService on the
    # remote download a file. This uses context.call_service(), which invokes a
    # special code path that causes auto-initialization of a thread pool in the
    # target, and auto-construction of the target service, but only if the
    # service call was made by a more privileged context. We could write a
    # helper function that runs in the remote to do all that by hand, but the
    # library handles it for us.

    # Make the file accessible. A future FileService could avoid the need for
    # this for privileged contexts.
    context.call_service(
        service_name=mitogen.service.FileService,
        method_name='register',
        path='/etc/passwd'
    )

    # Now we can use our streamy_download_file() function in reverse -- running
    # it from this process and having it fetch from the remote process:
    print("Streamy download /etc/passwd: result: %s" % (
        streamy_download_file(context, '/etc/passwd'),
    ))
1295987
def create_channel(data)
      channel = Channel.new(data, self)
      server = channel.server

      # Handle normal and private channels separately
      if server
        server.add_channel(channel)
        @channels[channel.id] = channel
      elsif channel.pm?
        @pm_channels[channel.recipient.id] = channel
      elsif channel.group?
        @channels[channel.id] = channel
      end
    end
728058
def create_listeners(address, port, logger=nil)
      unless port
        raise ArgumentError, "must specify port"
      end
      sockets = Socket.tcp_server_sockets(address, port)
      sockets = sockets.map {|s|
        s.autoclose = false
        TCPServer.for_fd(s.fileno)
      }
      return sockets
    end
737856
static <W, R> TcpClientImpl<W, R> _create(ClientState<W, R> state,
                                                                      TcpClientEventPublisher eventPublisher) {
        DetachedChannelPipeline channelPipeline = state.unsafeDetachedPipeline();
        state = state.channelProviderFactory(new TcpChannelProviderFactory(channelPipeline,
                                                                           state.getChannelProviderFactory()));

        HostConnectorFactory<W, R> hostConnectorFactory = new HostConnectorFactory<>(state, eventPublisher);

        ConnectionProvider<W, R> cp = state.getFactory()
                                             .newProvider(state.getHostStream().map(hostConnectorFactory));

        InterceptingTcpClient<W, R> interceptingTcpClient = new InterceptingTcpClientImpl<>(cp, eventPublisher);
        TcpClientImpl<W, R> client = new TcpClientImpl<>(state, eventPublisher, interceptingTcpClient);
        client.requestSetLazily = new ConnectionRequestImpl<>(cp);
        return client;
    }
481723
def create_connection
      @connection = Faraday.new(url: @api_host) do |builder|
        block_given? ? yield(builder) : Client.build_default_connection(builder)
      end
    end
1110983
def add_tcp_callback(self, port, callback, threaded_callback=False):
        
        if not callback:
            raise AttributeError("No callback")

        serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        serversocket.bind((_TCP_SOCKET_HOST, port))
        serversocket.listen(1)
        serversocket.setblocking(0)
        self._epoll.register(serversocket.fileno(), select.EPOLLIN)

        # Prepare the callback (wrap in Thread if needed)
        cb = callback if not threaded_callback else \
                partial(_threaded_callback, callback)

        self._tcp_server_sockets[serversocket.fileno()] = (serversocket, cb)
        debug("Socket server started at port %s and callback added." % port)
1028963
public function createConnection()
    {
        $address = $this->pool->getConnectionAddress();
        $timeout = $this->pool->getTimeout();
        list($host, $port) = explode(":", $address);

        $remoteSocket = sprintf('tcp://%s:%d', $host, $port);
        $fp           = stream_socket_client($remoteSocket, $errno, $errstr, $timeout);
        if (!$fp) {
            throw new RpcServerException(sprintf('stream_socket_client connect error errno=%s msg=%s', $errno, $errstr));
        }
        $this->connection = $fp;
    }
496810
private TransportClient createClient(InetSocketAddress address)
      throws IOException, InterruptedException {
    logger.debug("Creating new connection to {}", address);

    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup)
      .channel(socketChannelClass)
      // Disable Nagle's Algorithm since we don't want packets to wait
      .option(ChannelOption.TCP_NODELAY, true)
      .option(ChannelOption.SO_KEEPALIVE, true)
      .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.connectionTimeoutMs())
      .option(ChannelOption.ALLOCATOR, pooledAllocator);

    if (conf.receiveBuf() > 0) {
      bootstrap.option(ChannelOption.SO_RCVBUF, conf.receiveBuf());
    }

    if (conf.sendBuf() > 0) {
      bootstrap.option(ChannelOption.SO_SNDBUF, conf.sendBuf());
    }

    final AtomicReference<TransportClient> clientRef = new AtomicReference<>();
    final AtomicReference<Channel> channelRef = new AtomicReference<>();

    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
      @Override
      public void initChannel(SocketChannel ch) {
        TransportChannelHandler clientHandler = context.initializePipeline(ch);
        clientRef.set(clientHandler.getClient());
        channelRef.set(ch);
      }
    });

    // Connect to the remote server
    long preConnect = System.nanoTime();
    ChannelFuture cf = bootstrap.connect(address);
    if (!cf.await(conf.connectionTimeoutMs())) {
      throw new IOException(
        String.format("Connecting to %s timed out (%s ms)", address, conf.connectionTimeoutMs()));
    } else if (cf.cause() != null) {
      throw new IOException(String.format("Failed to connect to %s", address), cf.cause());
    }

    TransportClient client = clientRef.get();
    Channel channel = channelRef.get();
    assert client != null : "Channel future completed successfully with null client";

    // Execute any client bootstraps synchronously before marking the Client as successful.
    long preBootstrap = System.nanoTime();
    logger.debug("Connection to {} successful, running bootstraps...", address);
    try {
      for (TransportClientBootstrap clientBootstrap : clientBootstraps) {
        clientBootstrap.doBootstrap(client, channel);
      }
    } catch (Exception e) { // catch non-RuntimeExceptions too as bootstrap may be written in Scala
      long bootstrapTimeMs = (System.nanoTime() - preBootstrap) / 1000000;
      logger.error("Exception while bootstrapping client after " + bootstrapTimeMs + " ms", e);
      client.close();
      throw Throwables.propagate(e);
    }
    long postBootstrap = System.nanoTime();

    logger.info("Successfully created connection to {} after {} ms ({} ms spent in bootstraps)",
      address, (postBootstrap - preConnect) / 1000000, (postBootstrap - preBootstrap) / 1000000);

    return client;
  }
832328
def new_connection(self, remote_ip, remote_port):
        
        self.state.set_state('new')
        self._message = Message(Peer(remote_ip, remote_port))

        decision, response_sent = self.is_allowed('accept_new_connection',
                                                  self._message.peer)
        if decision:
            if not response_sent:
                self.handle_input('greet')
            self._set_size_restrictions()
        else:
            if not response_sent:
                self.reply(554, 'SMTP service not available')
            self.close_connection()
814237
def dhcp_server(create_if_not_found=true)
      return nil if interface_type != :host_only

      # Try to find the dhcp server in the list of DHCP servers.
      dhcp_name = "HostInterfaceNetworking-#{name}"
      result = parent.parent.dhcp_servers.find do |dhcp|
        dhcp.network_name == dhcp_name
      end

      # If no DHCP server is found, create one
      result = parent.parent.dhcp_servers.create(dhcp_name) if result.nil? && create_if_not_found
      result
    end
65595
protected function create()
    {

        // Create the remote address
        $remote_addr = sprintf("%s://%s:%d", $this->transport, $this->ip, $this->port);

        // Create context
        $context = stream_context_create([
            'socket' => [
                'bindto' => '0:0', // Bind to any available IP and OS decided port
            ],
        ]);

        // Define these first
        $errno = null;
        $errstr = null;

        // Create the socket
        if (($this->socket =
                @stream_socket_client($remote_addr, $errno, $errstr, $this->timeout, STREAM_CLIENT_CONNECT, $context))
            !== false
        ) {
            // Set the read timeout on the streams
            stream_set_timeout($this->socket, $this->timeout);

            // Set blocking mode
            stream_set_blocking($this->socket, $this->blocking);
        } else {
            // Reset socket
            $this->socket = null;

            // Something bad happened, throw query exception
            throw new Exception(
                __METHOD__ . " - Error creating socket to server {$this->ip}:{$this->port}. Error: " . $errstr,
                $errno
            );
        }
    }
1361018
def add_connection(caller_id) #:nodoc:
      connection = TCPROS::Server.new(@caller_id, @topic_name, @topic_type,
                                      :host=>@host,
                                      :latched=>@is_latched,
                                      :last_published_msg=>@last_published_msg)
      connection.start
      connection.id = "#{@topic_name}_out_#{@connection_id_number}"
      @connection_id_number += 1
      @connections.push(connection)
      return connection
    end
455708
def run
      logger.debug "Starting up..."
      @socket = TCPSocket.from_ruby_socket ::TCPSocket.new(@host, @port)
      post_init
      loop { receive_data @socket.readpartial(4096) }
    rescue EOFError, IOError, Errno::ECONNREFUSED => e
      logger.info "Client socket closed due to (#{e.class}) #{e.message}!"
      async.terminate
    end