// listen handles accepting and managing connections. However, since closer
// is len(1), it will not block the sender.
517221
func (s *server) listen(l net.Listener, conf *ssh.ServerConfig, closer chan interface{}) error {
	cxt := s.c
	log.Info(cxt, "Accepting new connections.")
	defer l.Close()

	// FIXME: Since Accept blocks, closer may not be checked often enough.
	for {
		log.Info(cxt, "Checking closer.")
		if len(closer) > 0 {
			<-closer
			log.Info(cxt, "Shutting down SSHD listener.")
			return nil
		}
		conn, err := l.Accept()
		if err != nil {
			log.Warnf(cxt, "Error during Accept: %s", err)
			// We shouldn't kill the listener because of an error.
			return err
		}
		safely.GoDo(cxt, func() {
			s.handleConn(conn, conf)
		})
	}
}
1028053
func (nm *Netmux) Listen(matchers ...Matcher) *Listener {
	l := &Listener{
		nm: nm,
	}
	return l
}
859127
func (p *AuthProxy) Listen() error {
	mux := bone.New()
	proxy := &httputil.ReverseProxy{
		Transport: p.t,
		Director: func(r *http.Request) {
			r.URL.Scheme = p.u.Scheme
			r.URL.Host = p.u.Host
			r.Host = p.u.Host
			r.URL.Path = r.URL.Path[6:]

			if p.sess.HasToken() {
				tok := string(p.sess.Token())
				r.Header["Authorization"] = []string{"Bearer " + tok}
			}

			r.Header["User-Agent"] = []string{"Torus-Daemon/" + p.c.Version}
			r.Header["X-Registry-Version"] = []string{p.c.APIVersion}
		},
	}

	go p.o.Start()

	mux.HandleFunc("/proxy/", proxyCanceler(proxy))
	mux.SubRoute("/v1", routes.NewRouteMux(p.c, p.sess, p.db, p.t, p.o, p.client, p.logic, p.updates))

	h := httpdown.HTTP{}
	p.s = h.Serve(&http.Server{Handler: requestIDHandler(loggingHandler(mux))}, p.l)

	return p.s.Wait()
}
795105
func (r *Receiver) Listen(h mq.Handler) (retErr error) {
	if !atomic.CompareAndSwapInt32(&r.state, stateCreated, stateConnecting) {
		return errors.New("pubsub: not in created state")
	}

	defer atomic.StoreInt32(&r.state, stateStopped)

	client, err := r.newClient()
	if err != nil {
		return err
	}

	defer func() {
		if err = client.Close(); err != nil && retErr != nil {
			retErr = err
		}
	}()

	atomic.StoreInt32(&r.state, stateListening)
	subscription := client.Subscription(r.subscriptionID)
	defer r.stopRecv()
	err = subscription.Receive(r.recvCtx, func(ctx context.Context, msg *pubsub.Message) {
		wrap := &message{msg: msg}
		h.Handle(wrap)
	})

	if err != context.Canceled {
		return err
	}

	return nil
}
1286676
func (b *Broker) listen() {
	for {
		select {
		case s := <-b.newClients:
			// A new client has connected.
			// Register their message channel.
			b.clients[s] = true
			golog.Infof("Client added. %d registered clients", len(b.clients))

		case s := <-b.closingClients:
			// A client has dettached and we want to
			// stop sending them messages.
			delete(b.clients, s)
			golog.Warnf("Removed client. %d registered clients", len(b.clients))

		case event := <-b.Notifier:
			// We got a new event from the outside!
			// Send event to all connected clients.
			for clientMessageChan := range b.clients {
				clientMessageChan <- event
			}

		}
	}
}
399780
func (l UnixListener) Listen() (net.Listener, error) {
	return net.FileListener(os.NewFile(l.Fd(), l.Path))
}
1296682
func Listen(addr, pkfile, certfile string) (net.Listener, error) {
	l, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, fmt.Errorf("Unable to listen for connections at %s: %s\n", addr, err)
	}

	return NewListenerAddr(l, addr, pkfile, certfile)
}
446324
func Listen(addr string) (net.Listener, error) {
	a := &Addr{s: addr}
	return a.Listen()
}
130595
func Listen(network, address string) (net.Listener, error) {
	if network == "unix" {
		return winio.ListenPipe(address, nil)
	}
	return net.Listen(network, address)
}
530719
func (b *Bootstrapper) Listen(addr string, cfgs ...iris.Configurator) {
	b.Run(iris.Addr(addr), cfgs...)
}
389217
func (r *rpcHandler) listen(ctx context.Context) {
	defer close(r.listenerCh)

	var acceptLoopDelay time.Duration
	for {
		select {
		case <-ctx.Done():
			r.logger.Info("closing server RPC connection")
			return
		default:
		}

		// Accept a connection
		conn, err := r.rpcListener.Accept()
		if err != nil {
			if r.shutdown {
				return
			}
			r.handleAcceptErr(ctx, err, &acceptLoopDelay)
			continue
		}
		// No error, reset loop delay
		acceptLoopDelay = 0

		go r.handleConn(ctx, conn, &RPCContext{Conn: conn})
		metrics.IncrCounter([]string{"nomad", "rpc", "accept_conn"}, 1)
	}
}
585952
func (l *ListenerConn) Listen(channel string) (bool, error) {
	return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel))
}
36198
func (mt *MultiplexTransport) Listen(addr NetAddress) error {
	ln, err := net.Listen("tcp", addr.DialString())
	if err != nil {
		return err
	}

	mt.netAddr = addr
	mt.listener = ln

	go mt.acceptPeers()

	return nil
}
298468
func Listen(httpBindAddr string, Asset func(string) ([]byte, error), exitCh chan int, registerCallback func(http.Handler)) {
	log.Info("[HTTP] Binding to address: %s", httpBindAddr)

	pat := pat.New()
	registerCallback(pat)

	//compress := handlers.CompressHandler(pat)
	auth := BasicAuthHandler(pat) //compress)

	err := http.ListenAndServe(httpBindAddr, auth)
	if err != nil {
		log.Fatalf("[HTTP] Error binding to address %s: %s", httpBindAddr, err)
	}
}
336935
func (s *ServerTLS) Listen() (net.Listener, error) {
	l, err := net.Listen("tcp", s.Addr[len(transport.TLS+"://"):])
	if err != nil {
		return nil, err
	}
	return l, nil
}
167551
func (dht *DHT) listen() {
	go func() {
		buff := make([]byte, 8192)
		for {
			n, raddr, err := dht.conn.ReadFromUDP(buff)
			if err != nil {
				continue
			}

			dht.packets <- packet{buff[:n], raddr}
		}
	}()
}
799545
func (c *xmppGcmClient) listen(h MessageHandler, stop <-chan bool) error {
	if stop != nil {
		go func() {
			select {
			case <-stop:
				// Set isClosed to 0 so we don't trigger an error when returning.
				c.Lock()
				c.XmppClient.Close()
				c.isClosed = true
				c.Unlock()

				// Remove client from cache.
				xmppClients.Lock()
				delete(xmppClients.m, c.senderID)
				xmppClients.Unlock()
			}
		}()
	}
	for {
		stanza, err := c.XmppClient.Recv()
		if err != nil {
			c.RLock()
			defer c.RUnlock()
			// If client is closed we can't return without error.
			if c.isClosed {
				return nil
			}
			// This is likely fatal, so return.
			return fmt.Errorf("error on Recv>%v", err)
		}
		v, ok := stanza.(xmpp.Chat)
		if !ok {
			continue
		}
		switch v.Type {
		case "":
			cm := &CcsMessage{}
			err = json.Unmarshal([]byte(v.Other[0]), cm)
			if err != nil {
				debug("Error unmarshaling ccs message: %v", err)
				continue
			}
			switch cm.MessageType {
			case CCSAck:
				c.messages.Lock()
				// ack for a sent message, delete it from log.
				if _, ok := c.messages.m[cm.MessageId]; ok {
					go h(*cm)
					delete(c.messages.m, cm.MessageId)
				}
				c.messages.Unlock()
			case CCSNack:
				// nack for a sent message, retry if retryable error, bubble up otherwise.
				if retryableErrors[cm.Error] {
					c.retryMessage(*cm, h)
				} else {
					c.messages.Lock()
					if _, ok := c.messages.m[cm.MessageId]; ok {
						go h(*cm)
						delete(c.messages.m, cm.MessageId)
					}
					c.messages.Unlock()
				}
			default:
				debug("Unknown ccs message: %v", cm)
			}
		case "normal":
			cm := &CcsMessage{}
			err = json.Unmarshal([]byte(v.Other[0]), cm)
			if err != nil {
				debug("Error unmarshaling ccs message: %v", err)
				continue
			}
			switch cm.MessageType {
			case CCSControl:
				// TODO(silvano): create a new connection, drop the old one 'after a while'
				debug("control message! %v", cm)
			case CCSReceipt:
				debug("receipt! %v", cm)
				// Receipt message: send ack and pass to listener.
				origMessageID := strings.TrimPrefix(cm.MessageId, "dr2:")
				ack := XmppMessage{To: cm.From, MessageId: origMessageID, MessageType: CCSAck}
				c.send(ack)
				go h(*cm)
			default:
				debug("uknown upstream message! %v", cm)
				// Upstream message: send ack and pass to listener.
				ack := XmppMessage{To: cm.From, MessageId: cm.MessageId, MessageType: CCSAck}
				c.send(ack)
				go h(*cm)
			}
		case "error":
			debug("error response %v", v)
		default:
			debug("unknown message type %v", v)
		}
	}
}