:param accept_callback: Called with `Win32PipeConnection` when a new
        connection is established.
344373
def bind_and_listen_on_win32_socket(socket_name, accept_callback):
    
    assert callable(accept_callback)
    socket_name = r'\\.\pipe\pymux.sock.jonathan.42'

    pipes = [PipeInstance(socket_name, pipe_connection_cb=accept_callback)
             for i in range(INSTANCES)]

    for p in pipes:
        # Start pipe.
        ensure_future(p.handle_pipe())

    return socket_name
973776
function _handleConnection(client) {
	client.on('message', curry(_handleMessage, client))
	client.on('disconnect', curry(_handleDisconnect, client))
	client.pubsub = _engine.getPubSub()
	_emitter.emit('client_connect', client)
}
948317
function (_callback)
    {
        if (_callback) {
            _callback = _callback.bind(this._conn);
        } else {
            _callback = this._conn._connect_cb.bind(this._conn);
        }
        var body = this._buildBody();
        this._requests.push(
                new Strophe.Request(body.tree(),
                    this._onRequestStateChange.bind(
                        this, _callback.bind(this._conn)),
                    body.tree().getAttribute("rid")));
        this._throttledRequestHandler();
    }
492949
def _subthread_handle_accepted(self, client):
        

        conn, addr = client
        if self.handle_incoming(conn, addr):
            logging.info('Accepted connection from client: {}'.format(addr))
            conn.setblocking(False)
            self.clients[conn] = addr
            self.register(conn)
        else:
            logging.info('Refused connection from client: {}'.format(addr))
            self.disconnect(conn)
1264076
def add_callback(self, name, func):
        

        if name == 'on_scan':
            events = ['device_seen']
            def callback(_conn_string, _conn_id, _name, event):
                func(self.id, event, event.get('validity_period', 60))
        elif name == 'on_report':
            events = ['report', 'broadcast']
            def callback(_conn_string, conn_id, _name, event):
                func(conn_id, event)
        elif name == 'on_trace':
            events = ['trace']
            def callback(_conn_string, conn_id, _name, event):
                func(conn_id, event)
        elif name == 'on_disconnect':
            events = ['disconnection']
            def callback(_conn_string, conn_id, _name, _event):
                func(self.id, conn_id)
        else:
            raise ArgumentError("Unknown callback type {}".format(name))

        self._adapter.register_monitor([None], events, callback)
1044857
public C accept() throws IOException {
		try {
			synchronized(this){
				if (connState != CONN_STATE_READY_FOR_ACCEPT) {
					throw new IOException("bind needs to be called before accept (1), current state =" + connState);
				}
				logger.info("starting accept");
				if (requested.peek() == null){
					wait();
				}
			}
			C endpoint = requested.poll();
			logger.info("connect request received");
			endpoint.accept();
			return endpoint;
		} catch (Exception e) {
			throw new IOException(e);
		}
	}
230864
def _maybe_connect(self, to_pid, callback=None):
    """"""

    callback = stack_context.wrap(callback or (lambda stream: None))

    def streaming_callback(data):
      # we are not guaranteed to get an acknowledgment, but log and discard bytes if we do.
      log.info('Received %d bytes from %s, discarding.' % (len(data), to_pid))
      log.debug('  data: %r' % (data,))

    def on_connect(exit_cb, stream):
      log.info('Connection to %s established' % to_pid)
      with self._connection_callbacks_lock:
        self._connections[to_pid] = stream
      self.__dispatch_on_connect_callbacks(to_pid, stream)
      self.__loop.add_callback(
          stream.read_until_close,
          exit_cb,
          streaming_callback=streaming_callback)

    create = False
    with self._connection_callbacks_lock:
      stream = self._connections.get(to_pid)
      callbacks = self._connection_callbacks.get(to_pid)

      if not stream:
        self._connection_callbacks[to_pid].append(callback)

        if not callbacks:
          create = True

    if stream:
      self.__loop.add_callback(callback, stream)
      return

    if not create:
      return

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
    if not sock:
      raise self.SocketError('Failed opening socket')

    stream = IOStream(sock, io_loop=self.__loop)
    stream.set_nodelay(True)
    stream.set_close_callback(partial(self.__on_exit, to_pid, b'reached end of stream'))

    connect_callback = partial(on_connect, partial(self.__on_exit, to_pid), stream)

    log.info('Establishing connection to %s' % to_pid)

    stream.connect((to_pid.ip, to_pid.port), callback=connect_callback)

    if stream.closed():
      raise self.SocketError('Failed to initiate stream connection')

    log.info('Maybe connected to %s' % to_pid)
683806
function(callback) {
      self._getConnection(function(err, connection) {
        if (err) {
          callback(new Error('Unable to establish connection with the master ' +
                             'process'));
          return;
        }

        self._connection = connection;
        callback();
      });
    }
1364308
def connect(self):
        
        self.client = BaitTelnetClient(self.options['server'], self.options['port'])
        self.client.set_option_negotiation_callback(self.process_options)
210890
def _on_connection_open(self, connection):
        
        _log.info("Successfully opened connection to %s", connection.params.host)
        self._channel = connection.channel(on_open_callback=self._on_channel_open)
88976
def do_async_recv(self, bufsize):
        
        data = self.sock.recv(bufsize)

        if len(data) == 0:
            raise socket.error('no data to receive')

        self.recvbuf += data

        while contains_frame(self.recvbuf):
            frame, self.recvbuf = pop_frame(self.recvbuf)
            frame = self.apply_recv_hooks(frame, False)

            if not self.recv_callback:
                raise ValueError('no callback installed for %s' % frame)

            self.recv_callback(frame)
523000
def on_welcome(self, c, e):
        
        self.backoff = 1  # Assume we had a good connection. Reset backoff.
        if self.nickserv:
            if Utilities.isNotEmpty(self.nickserv_pass):
                self.identify(c, e, self.nickserv_pass)
                time.sleep(3)  # Make sure Nickserv really sees us
            else:
                logger.error('If nickserv is enabled, you must supply'
                             ' a password')

        if self.nickserv is False and self.nickserv_pass is not None:
            logger.warn('It appears you provided a nickserv password but '
                        'did not enable nickserv authentication')

        for channel in self.my_channels:
            logger.debug('Attempting to join {0!s}'.format(channel))
            c.join(channel)
1321275
def set_close_callback(self, cb):
        
        assert self._close_cb is None, (
            'A close_callback has already been set for this connection.'
        )
        self._close_cb = stack_context.wrap(cb)
        if self.closed:
            self._close_cb()
941853
def client_connected_callback(self, reader, writer):
        """"""
        peer = writer.get_extra_info('peername')
        clients.append((reader, writer, peer))
        log.info("Incoming connection from: %s:%s", peer[0], peer[1])
        try:
            while True:
                data = yield from reader.readline()
                if not data:
                    break
                try:
                    line = data.decode().strip()
                except UnicodeDecodeError:
                    line = '\x00'

                # Workaround for domoticz issue #2816
                if line[-1] != DELIM:
                    line = line + DELIM

                if valid_packet(line):
                    yield from self.handle_raw_tx_packet(writer, line)
                else:
                    log.warning(" %s:%s: dropping invalid data: '%s'", peer[0], peer[1], line)
                    pass
        except ConnectionResetError:
            pass
        except Exception as e:
            log.exception(e)

        log.info("Disconnected from: %s:%s", peer[0], peer[1])
        writer.close()
        clients.remove((reader, writer, peer))
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)
840264
def _accept_loop(self):
        """"""
        self._listening_sock.setblocking(0)
        while not self._stopped and not _shutting_down:
            try:
                # Wait a short time to accept.
                if select.select([self._listening_sock.fileno()], [], [], 1):
                    client, client_addr = self._listening_sock.accept()
                    client.setblocking(True)
                    self._log('connection from %s' % format_addr(client_addr))
                    server_thread = threading.Thread(
                        target=functools.partial(
                            self._server_loop, client, client_addr))

                    # Store weakrefs to the thread and socket, so we can
                    # dispose them in stop().
                    self._server_threads[server_thread] = None
                    self._server_socks[client] = None

                    server_thread.daemon = True
                    server_thread.start()
            except socket.error as error:
                if error.errno not in (
                    errno.EAGAIN, errno.EBADF, errno.EWOULDBLOCK):
                    raise
            except select.error as error:
                if error.args[0] == errno.EBADF:
                    # Closed.
                    break
                else:
                    raise
807298
def service_confirmation(self, conn, bslpdu):
        """"""
        if _debug: ProxyServerService._debug("service_confirmation %r %r", conn, bslpdu)

        # make sure there is an adapter for it - or something went wrong
        if not getattr(conn, 'proxyAdapter', None):
            raise RuntimeError("service confirmation received but no adapter for it")

        # forward along
        conn.proxyAdapter.service_confirmation(bslpdu)