binds to a port, waits for the debugger to connect
490923
def start_server(port):
    '''  '''
    s = socket(AF_INET, SOCK_STREAM)
    s.settimeout(None)

    try:
        from socket import SO_REUSEPORT
        s.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
    except ImportError:
        s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

    s.bind(('', port))
    pydev_log.info("Bound to port :%s", port)

    try:
        s.listen(1)
        newSock, _addr = s.accept()
        pydev_log.info("Connection accepted")
        # closing server socket is not necessary but we don't need it
        s.shutdown(SHUT_RDWR)
        s.close()
        return newSock

    except:
        pydev_log.exception("Could not bind to port: %s\n", port)
23933
function (ui, done) {

        var bs          = ui.bs;
        var port        = ui.options.get("port");
        var listenHost  = ui.options.get("listen");

        ui.logger.debug("Using port %s", port);

        var server = require("./server")(ui, {
            middleware: {
                socket: bs.getMiddleware("socket-js"),
                connector: bs.getSocketConnector(bs.options.get("port"), {
                    path: bs.options.getIn(["socket", "path"]),
                    namespace: ui.config.getIn(["socket", "namespace"])
                })
            }
        });

        require('server-destroy')(server.server);

        bs.registerCleanupTask(function () {
            if (server.server) {
                server.server.destroy();
            }
            if (ui.servers) {
                Object.keys(ui.servers).forEach(function (key) {
                    if (ui.servers[key].server) {
                        ui.servers[key].server.destroy();
                    }
                });
            }
        });

        done(null, {
            instance: {
                server: server.server.listen(port, listenHost),
                app: server.app
            }
        });

    }
1145509
def _connect(self):
        """"""
        try:
            while True:
                _LOGGER.info('Trying to connect to %s', self.port)
                try:
                    yield from serial_asyncio.create_serial_connection(
                        self.loop, lambda: self.protocol, self.port, self.baud)
                    return
                except serial.SerialException:
                    _LOGGER.error('Unable to connect to %s', self.port)
                    _LOGGER.info(
                        'Waiting %s secs before trying to connect again',
                        self.reconnect_timeout)
                    yield from asyncio.sleep(
                        self.reconnect_timeout, loop=self.loop)
        except asyncio.CancelledError:
            _LOGGER.debug('Connect attempt to %s cancelled', self.port)
1313358
def server_bind(self):
        """"""
        socketserver.TCPServer.server_bind(self)
        host, port = self.socket.getsockname()[:2]
        self.server_name = socket.getfqdn(host)
        self.server_port = port
723343
def _waitForSSHPort(self):
        
        logger.debug('Waiting for ssh port to open...')
        for i in count():
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                s.settimeout(a_short_time)
                s.connect((self.effectiveIP, 22))
                logger.debug('...ssh port open')
                return i
            except socket.error:
                pass
            finally:
                s.close()
1137620
private static void waitForStop(TestContainer testContainer, int localPort) {
        try {
            ServerSocket serverSocket = new ServerSocket(localPort);
            Socket socket = serverSocket.accept();

            InputStreamReader isr = new InputStreamReader(socket.getInputStream(), "UTF-8");
            BufferedReader reader = new BufferedReader(isr);
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
            PrintWriter pw = new PrintWriter(writer, true);
            boolean running = true;
            while (running) {
                String command = reader.readLine();
                LOG.debug("command = {}", command);
                if (command.equals("stop")) {
                    testContainer.stop();
                    pw.println("stopped");
                    writer.flush();
                    LOG.info("test container stopped");
                }
                else if (command.equals("quit")) {
                    LOG.debug("quitting PaxExamRuntime");
                    pw.close();
                    socket.close();
                    serverSocket.close();
                    running = false;
                }
            }
        }
        catch (IOException exc) {
            LOG.debug("socket error", exc);
        }
    }
1170878
protected synchronized void bind(InetAddress address, int lport)
        throws IOException
    {
       synchronized (fdLock) {
            if (!closePending && (socket == null || !socket.isBound())) {
                NetHooks.beforeTcpBind(fd, address, lport);
            }
        }
        socketBind(address, lport);
        if (socket != null)
            socket.setBound();
        if (serverSocket != null)
            serverSocket.setBound();
    }
37005
function (ui, done) {
        var port = ui.options.get("port");
        var listenHost = ui.options.get("listen", "localhost");
        ui.bs.utils.portscanner.findAPortNotInUse(port, port + 100, {
            host: listenHost,
            timeout: 1000
        }, function (err, port) {
            if (err) {
                return done(err);
            }
            done(null, {
                options: {
                    port: port
                }
            });
        });
    }
125899
def wait_transmit(self, *ports):
        

        port_list = self.set_ports_list(*ports)
        self.api.call_rc('ixCheckTransmitDone {}'.format(port_list))
121921
def connect(self, url=c.LOCALHOST, port=None, timeout=c.INITIAL_TIMEOUT,
                      debug=False):
        """"""
        if port != None: # force a selection to a new port
            if self._port!=None: # if previously allocated port, return it
                portpicker.return_port(self._port)
            self._port = port
        elif self._port==None: # no connection exists
            self._port = portpicker.pick_unused_port()
        self._url = url
        if ":" in url and not url.startswith("["):  # Support ipv6 addresses.
            url = "[%s]" % url
        for i in range(timeout):
            startTime = time.time()
            if debug:
                print("attempt #%d to websocket connect to %s:%s"%(i, url, port))
            try:
                finalUrl = "ws://%s:%s/sc2api" %(url, self._port)
                ws = websocket.create_connection(finalUrl, timeout=timeout)
                #print("ws:", ws)
                self._client = protocol.StarcraftProtocol(ws)
                #super(ClientController, self).__init__(client) # ensure RemoteController initializtion is performed
                #if self.ping(): print("init ping()") # ensure the latest state is synced
                # ping returns:
                #   game_version:   "4.1.2.60604"
                #   data_version:   "33D9FE28909573253B7FC352CE7AEA40"
                #   data_build:     60604
                #   base_build:     60321
                return self
            except socket.error: pass  # SC2 hasn't started listening yet.
            except websocket.WebSocketException as err:
                print(err, type(err))
                if "Handshake Status 404" in str(err):
                    pass  # SC2 is listening, but hasn't set up the /sc2api endpoint yet.
                else: raise
            except Exception as e:
                print(type(e), e)
            sleepTime = max(0, 1 - (time.time() - startTime)) # try to wait for up to 1 second total
            if sleepTime:   time.sleep(sleepTime)
        raise websocket.WebSocketException("Could not connect to game at %s on port %s"%(url, port))
878274
def __check_port(self, port):
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            s.bind((_host(), port))
            return True
        except socket.error:
            return False
        finally:
            s.close()
980951
async def debug(self, conn_id, name, cmd_args):
        

        adapter_id = self._get_property(conn_id, 'adapter')
        return await self.adapters[adapter_id].debug(conn_id, name, cmd_args)
794019
def _connect_temporarily(self, port_v, target=True):
        
        if target:
            handle = self._connection_v.to_handle()
        else:
            handle = self._connection_v.from_handle()
        port_v.add_connected_handle(handle, self._connection_v, moving=True)
        port_v.tmp_connect(handle, self._connection_v)
        self._connection_v.set_port_for_handle(port_v, handle)
        # Redraw state of port to make hover state visible
        self._redraw_port(port_v)
883890
public void connect(final String serialPortName)
			throws SerialInterfaceException {
		logger.info("Connecting to serial port {}", serialPortName);
		try {
			CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
			CommPort commPort = portIdentifier.open("org.openhab.binding.zwave",2000);
			this.serialPort = (SerialPort) commPort;
			this.serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
			this.serialPort.enableReceiveThreshold(1);
			this.serialPort.enableReceiveTimeout(ZWAVE_RECEIVE_TIMEOUT);
			this.receiveThread = new ZWaveReceiveThread();
			this.receiveThread.start();
			this.sendThread = new ZWaveSendThread();
			this.sendThread.start();

			logger.info("Serial port is initialized");
		} catch (NoSuchPortException e) {
			logger.error(e.getLocalizedMessage());
			throw new SerialInterfaceException(e.getLocalizedMessage(), e);
		} catch (PortInUseException e) {
			logger.error(e.getLocalizedMessage());
			throw new SerialInterfaceException(e.getLocalizedMessage(), e);
		} catch (UnsupportedCommOperationException e) {
			logger.error(e.getLocalizedMessage());
			throw new SerialInterfaceException(e.getLocalizedMessage(), e);
		}
	}
780263
def wait_for(port_num, timeout):
    
    logger.debug("wait for {port_num}".format(**locals()))
    t_start = time.time()
    sleeps = 0.1
    while time.time() - t_start < timeout:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                s.connect((_host(), port_num))
                return True
            except (IOError, socket.error):
                time.sleep(sleeps)
        finally:
            s.close()
    return False
980180
function(selectedPort, callback) {
        if(selectedPort === false)
          grunt.fatal('No available port was found')

        self.data.targets.forEach(function(prop) {
          pp.injectPort(prop, selectedPort)
        })

        if(pp.options.name) {
          pp.injectPort(pp.options.name, selectedPort)
        }

        callback(null)
        return
      }
1144874
def _connect(self):
        """"""
        while self.protocol:
            _LOGGER.info('Trying to connect to %s', self.port)
            try:
                ser = serial.serial_for_url(
                    self.port, self.baud, timeout=self.timeout)
            except serial.SerialException:
                _LOGGER.error('Unable to connect to %s', self.port)
                _LOGGER.info(
                    'Waiting %s secs before trying to connect again',
                    self.reconnect_timeout)
                time.sleep(self.reconnect_timeout)
            else:
                transport = serial.threaded.ReaderThread(
                    ser, lambda: self.protocol)
                transport.daemon = False
                poll_thread = threading.Thread(target=self._poll_queue)
                self._stop_event.clear()
                poll_thread.start()
                transport.start()
                transport.connect()
                return