Directly launch the remote agent and connect JDI to it with a
ListeningConnector.
963277
private VirtualMachine listenTarget(int port, List<String> remoteVMOptions) {
        ListeningConnector listener = (ListeningConnector) connector;
        // Files to collection to output of a start-up failure
        File crashErrorFile = createTempFile("error");
        File crashOutputFile = createTempFile("output");
        try {
            // Start listening, get the JDI connection address
            String addr = listener.startListening(connectorArgs);
            debug("Listening at address: " + addr);

            // Launch the RemoteAgent requesting a connection on that address
            String javaHome = System.getProperty("java.home");
            List<String> args = new ArrayList<>();
            args.add(javaHome == null
                    ? "java"
                    : javaHome + File.separator + "bin" + File.separator + "java");
            args.add("-agentlib:jdwp=transport=" + connector.transport().name() +
                    ",address=" + addr);
            args.addAll(remoteVMOptions);
            args.add(remoteAgent);
            args.add("" + port);
            ProcessBuilder pb = new ProcessBuilder(args);
            pb.redirectError(crashErrorFile);
            pb.redirectOutput(crashOutputFile);
            process = pb.start();

            // Accept the connection from the remote agent
            vm = timedVirtualMachineCreation(() -> listener.accept(connectorArgs),
                    () -> process.waitFor());
            try {
                listener.stopListening(connectorArgs);
            } catch (IOException | IllegalConnectorArgumentsException ex) {
                // ignore
            }
            crashErrorFile.delete();
            crashOutputFile.delete();
            return vm;
        } catch (Throwable ex) {
            if (process != null) {
                process.destroyForcibly();
            }
            try {
                listener.stopListening(connectorArgs);
            } catch (IOException | IllegalConnectorArgumentsException iex) {
                // ignore
            }
            String text = readFile(crashErrorFile) + readFile(crashOutputFile);
            crashErrorFile.delete();
            crashOutputFile.delete();
            if (text.isEmpty()) {
                throw reportLaunchFail(ex, "listen");
            } else {
                throw new IllegalArgumentException(text);
            }
        }
    }
226133
protected void remoteInit() throws JMSException
    {
        CreateConsumerQuery query = new CreateConsumerQuery();
        query.setConsumerId(id);
        query.setSessionId(session.getId());
        query.setDestination(destination);
        query.setMessageSelector(messageSelector);
        query.setNoLocal(noLocal);
        transportEndpoint.blockingRequest(query);        
    }
555554
def connect(self, protocol=None, mode=None, disposition=None):
        """"""
        self.component.connect(protocol, mode, disposition)
208381
def run(self):
        """"""
        # Launch the broker(s)
        for hostname, nb_brokers in self.broker_hosts:
            for ind in range(nb_brokers):
                if self.externalHostname in utils.localHostnames:
                    self.brokers.append(localBroker(
                        debug=self.debug,
                        nice=self.nice,
                        backend=self.backend,
                    ))
                else:
                    self.brokers.append(remoteBroker(
                        hostname=hostname,
                        pythonExecutable=self.python_executable,
                        debug=self.debug,
                        nice=self.nice,
                        backend=self.backend,
                        rsh=self.rsh,
                        ssh_executable=self.ssh_executable,
                    ))

        # Share connection information between brokers
        if self.b > 1:
            for broker in self.brokers:
                # Only send data of other brokers to a given broker
                connect_data = [
                    BrokerInfo(
                        x.getHost(),
                        *x.getPorts(),
                        externalHostname=x.getHost()
                    )
                    for x in self.brokers
                    if x is not broker
                ]
                broker.sendConnect(connect_data)

        # Launch the workers
        shells = []
        origin_launched = False
        for hostname, nb_workers in self.worker_hosts:
            self.workers.append(self.LAUNCH_HOST_CLASS(hostname, self.rsh,
                                                       self.ssh_executable))
            total_workers_host = min(nb_workers, self.workersLeft)

            self.setWorkerInfo(hostname, total_workers_host, not origin_launched)
            origin_launched = True
            self.workersLeft -= total_workers_host

            # Launch every workers at the same time
            scoop.logger.debug(
                "{0}: Launching '{1}'".format(
                    hostname,
                    self.workers[-1].getCommand(),
                )
            )
            shells.append(self.workers[-1].launch(
                (self.brokers[0].brokerPort,
                 self.brokers[0].infoPort)
                    if self.tunnel else None,
            ))
            if self.workersLeft <= 0:
                # We've launched every worker we needed, so let's exit the loop
                break
        rootProcess = shells[0][0]

        # Wait for the root program
        try:
            if self.workers[0].isLocal():
                self.errors = self.workers[0].subprocesses[0].wait()
            else:
                self.errors = rootProcess.wait()
        except KeyboardInterrupt:
            pass
        scoop.logger.info('Root process is done.')
        return self.errors
1148032
async def _async_connect(self):  # pragma: no cover
        
        try:
            self.conn_coro = self.client.connected()
            aenter = type(self.conn_coro).__aenter__(self.conn_coro)
            self.stream = await aenter
            logger.info(f"Agent {str(self.jid)} connected and authenticated.")
        except aiosasl.AuthenticationFailure:
            raise AuthenticationFailure(
                "Could not authenticate the agent. Check user and password or use auto_register=True")
360828
def main(url):
    """"""
    try:
        listener = ListenerWorker(url)
        listener.connect()
        listener.run_forever()
    except KeyboardInterrupt:
        listener.close()
468779
def remote_profile(script, argv, profiler_factory, interval, spawn, signum,
                   pickle_protocol, endpoint, verbose):
    
    filename, code, globals_ = script
    sys.argv[:] = [filename] + list(argv)
    # create listener.
    listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind(endpoint)
    listener.listen(1)
    # be verbose or quiet.
    if verbose:
        log = lambda x: click.echo(click.style('> ', fg='cyan') + x)
        bound_addr = listener.getsockname()
        log('Listening on {0}:{1} for profiling...'.format(*bound_addr))
    else:
        log = noop
    # start profiling server.
    frame = sys._getframe()
    profiler = profiler_factory(base_frame=frame, base_code=code)
    profiler_trigger = BackgroundProfiler(profiler, signum)
    profiler_trigger.prepare()
    server_args = (interval, log, pickle_protocol)
    server = SelectProfilingServer(listener, profiler_trigger, *server_args)
    spawn(server.serve_forever)
    # exec the script.
    try:
        exec_(code, globals_)
    except KeyboardInterrupt:
        pass
751454
private void connect() throws IOReactorException
    {
        if (m_connManager == null) {
            ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
            m_connManager = new PoolingNHttpClientConnectionManager(ioReactor);
            m_connManager.setMaxTotal(HTTP_EXPORT_MAX_CONNS);
            m_connManager.setDefaultMaxPerRoute(HTTP_EXPORT_MAX_CONNS);
        }

        if (m_client == null || !m_client.isRunning()) {
            HttpAsyncClientBuilder client = HttpAsyncClients.custom().setConnectionManager(m_connManager);

            if (m_isKrb) {
                // m_client = (CloseableHttpAsyncClient)Subject.doAs(m_context.getSubject(), new PrivilegedBuild(client));
            }
            else {
                m_client = client.build();
            }
            m_client.start();
        }
    }
614987
def run(self):
        
        listen_socket = self.create_socket(self.host, self.port)
        logger.info('Listening for telnet connections on %s port %r', self.host, self.port)

        try:
            while True:
                # Removed closed connections.
                self.connections = set([c for c in self.connections if not c.closed])

                # Ignore connections handling commands.
                connections = set([c for c in self.connections if not c.handling_command])

                # Wait for next event.
                read_list = (
                    [listen_socket, self._schedule_pipe[0]] +
                    [c.conn for c in connections])

                read, _, _ = select.select(read_list, [], [])

                for s in read:
                    # When the socket itself is ready, accept a new connection.
                    if s == listen_socket:
                        self._accept(listen_socket)

                    # If we receive something on our "call_from_executor" pipe, process
                    # these callbacks in a thread safe way.
                    elif s == self._schedule_pipe[0]:
                        self._process_callbacks()

                    # Handle incoming data on socket.
                    else:
                        self._handle_incoming_data(s)
        finally:
            listen_socket.close()
305551
public boolean connect() {
        if (client.isConnected()) {
            logger.warn("Already connected");
            return true;
        }
        try {
            logger.info("Connecting to remote host " + remoteHost);
            client.connect(remoteHost);
            client.rlogin(localUser, remoteUser, terminalType);
            writer = new OutputStreamWriter(client.getOutputStream());
            outputReaderThread = new Thread(new OutputReader());
            outputReaderThread.start();
            if (interactive) {
                standardInputReaderThread = new Thread(new StandardInputReader());
                standardInputReaderThread.start();
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException ex) {
            }
            if (client.isConnected()) {
                return true;
            } else {
                logger.fatal("Client has been immediately disconnected from remote host:" + remoteHost);
                return false;
            }
            //outputReaderThread.
        } catch (IOException e) {
            logger.fatal("Could not connect to remote host:" + remoteHost, e);
            return false;
        }
    }
1226874
async def startlisten(self, connmark = -1):
        '''
        
        '''
        if connmark is None:
            connmark = self.connmark
        self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.STARTLISTEN, True, connmark))
1035744
def connect(self, host, port=6667, password=None):
        
        # Prepare the callbacks
        self._irc.add_global_handler('all_events', self.__handler)

        # Prepare the connection
        self._connection = self._irc.server().connect(
            host, port, self._nickname, password,
            self._username, self._realname)

        # Start connection thread
        self.__stopped.clear()
        self.__thread = threading.Thread(target=self.__loop,
                                         name="IRC-Bot-Loop")
        self.__thread.daemon = True
        self.__thread.start()
491705
private void setupAudioChannelOutbound(MediaDescriptionField remoteAudio) throws IOException {
        // Negotiate audio codecs
        this.audioChannel.negotiateFormats(remoteAudio);
        if (!this.audioChannel.containsNegotiatedFormats()) {
            throw new IOException("Audio codecs were not supported");
        }

        // connect to remote peer - RTP
        String remoteRtpAddress = remoteAudio.getConnection().getAddress();
        int remoteRtpPort = remoteAudio.getPort();

        // only connect is calls are plain old SIP
        // For WebRTC cases, the ICE Agent must connect upon candidate selection
        boolean connectNow = !(this.outbound && audioChannel.isIceEnabled());
        if (connectNow) {
            this.audioChannel.connectRtp(remoteRtpAddress, remoteRtpPort);
            // connect to remote peer - RTCP
            boolean remoteRtcpMux = remoteAudio.isRtcpMux();
            if (remoteRtcpMux) {
                this.audioChannel.connectRtcp(remoteRtpAddress, remoteRtpPort);
            } else {
                RtcpAttribute remoteRtcp = remoteAudio.getRtcp();
                if (remoteRtcp == null) {
                    // No specific RTCP port, so default is RTP port + 1
                    this.audioChannel.connectRtcp(remoteRtpAddress, remoteRtpPort + 1);
                } else {
                    // Specific RTCP address and port contained in SDP
                    String remoteRtcpAddress = remoteRtcp.getAddress();
                    if (remoteRtcpAddress == null) {
                        // address is optional in rtcp attribute
                        // will match RTP address if not defined
                        remoteRtcpAddress = remoteRtpAddress;
                    }
                    int remoteRtcpPort = remoteRtcp.getPort();
                    this.audioChannel.connectRtcp(remoteRtcpAddress, remoteRtcpPort);
                }
            }
        }
    }
470031
def connect(self):
        """"""
        device = None
        # logger.debug("Connecting to: {}".format(str(self)))
        for device in self.devices:
            if not device.connected:
                self.connection.emit_message("Connecting {}".format(str(device)), log_level=logging.INFO)
                protocol_name = device.get_protocol_name()
                device.protocol = make_protocol(protocol_name, device)
                command = device.protocol.get_command()
                self.ctrl.spawn_session(command=command)
                try:
                    result = device.connect(self.ctrl)
                except CommandSyntaxError as exc:
                    # all commands during discovery provides itself in exception except
                    # spawn session which is handled differently. If command syntax error is detected during spawning
                    # a new session then the problem is either on jumphost or csm server.
                    # The problem with spawning session is detected in connect FSM for telnet and ssh.
                    if exc.command:
                        cmd = exc.command
                        host = device.hostname
                    else:
                        cmd = command
                        host = "Jumphost/CSM"

                    self.connection.log(
                        "Command not supported or not authorized on {}: '{}'".format(host, cmd))
                    raise CommandError(message="Command not supported or not authorized",
                                       command=cmd,
                                       host=host)

                if result:
                    # logger.info("Connected to {}".format(device))
                    self.connection.emit_message("Connected {}".format(device), log_level=logging.INFO)
                else:
                    if device.last_error_msg:
                        message = device.last_error_msg
                        device.last_error_msg = None
                    else:
                        message = "Connection error"

                    self.connection.log(message)
                    raise ConnectionError(message)  # , host=str(device))

        if device is None:
            raise ConnectionError("No devices")

        return True
276074
def execute_remote(self, remote_target, cmd, **kwargs):
        
        data = self._build_command(cmd, kwargs, self._contexts[-1],
                                   remote_target)
        with self._lock:
            rootelem = self.transport.send(data)
        try:
            return self._build_response(rootelem)
        except ElementNotFoundException:
            xlog.exception("XCLIClient.execute")
            raise chained(CorruptResponse(rootelem))
        except Exception as e:
            xlog.exception("XCLIClient.execute")
            raise e
833828
protected synchronized void connect()
    {
        if (api.getStatus() != JDA.Status.ATTEMPTING_TO_RECONNECT)
            api.setStatus(JDA.Status.CONNECTING_TO_WEBSOCKET);
        if (shutdown)
            throw new RejectedExecutionException("JDA is shutdown!");
        initiating = true;

        String url = api.getGatewayUrl() + "?encoding=json&v=" + DISCORD_GATEWAY_VERSION;
        if (compression)
        {
            url += "&compress=zlib-stream";
            decompressBuffer = newDecompressBuffer();
        }

        try
        {
            socket = api.getWebSocketFactory()
                    .createSocket(url)
                    .addHeader("Accept-Encoding", "gzip")
                    .addListener(this);
            socket.connect();
        }
        catch (IOException | WebSocketException e)
        {
            api.resetGatewayUrl();
            //Completely fail here. We couldn't make the connection.
            throw new IllegalStateException(e);
        }
    }
822392
def start_listener(self):
        ''''''
        if self.sock is not None:
            self.sock.close()
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.bind(('', self.asterix_settings.port))
        self.sock.setblocking(False)
        print("Started on port %u" % self.asterix_settings.port)