当前位置: 首页>>代码示例>>Golang>>正文


Golang TCPListener.Addr方法代码示例

本文整理汇总了Golang中net.TCPListener.Addr方法的典型用法代码示例。如果您正苦于以下问题:Golang TCPListener.Addr方法的具体用法?Golang TCPListener.Addr怎么用?Golang TCPListener.Addr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net.TCPListener的用法示例。


在下文中一共展示了TCPListener.Addr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: acceptTCP

// Accept accepts connections on the listener and serves requests
// for each incoming connection.  Accept blocks; the caller typically
// invokes it in a go statement.
func acceptTCP(server *Server, lis *net.TCPListener) {
	var (
		conn *net.TCPConn
		err  error
		r    int
	)
	for {
		if conn, err = lis.AcceptTCP(); err != nil {
			// if listener close then return
			log.Error("listener.Accept(\"%s\") error(%v)", lis.Addr().String(), err)
			return
		}
		if err = conn.SetKeepAlive(Conf.TCPKeepalive); err != nil {
			log.Error("conn.SetKeepAlive() error(%v)", err)
			return
		}
		if err = conn.SetReadBuffer(Conf.TCPSndbuf); err != nil {
			log.Error("conn.SetReadBuffer() error(%v)", err)
			return
		}
		if err = conn.SetWriteBuffer(Conf.TCPRcvbuf); err != nil {
			log.Error("conn.SetWriteBuffer() error(%v)", err)
			return
		}
		go serveTCP(server, conn, r)
		if r++; r == maxInt {
			r = 0
		}
	}
}
开发者ID:vincentqiu,项目名称:goim,代码行数:33,代码来源:tcp.go

示例2: runWebApi

func runWebApi(listener *net.TCPListener, store *StoreChan, staticDir string) (err error) {
	var sessions *webSessionFactory
	if sessions, err = NewWebSessionFactory(600 * time.Second); err != nil { // TODO: hardcoded value
		return err
	}

	http.Handle("/api/authenticate", webHandler{store, sessions, handleWebAuthenticate})
	http.Handle("/api/add", webHandler{store, sessions, handleWebAdd})
	http.Handle("/api/remove", webHandler{store, sessions, handleWebRemove})
	http.Handle("/api/update", webHandler{store, sessions, handleWebUpdate})
	http.Handle("/api/set-admin", webHandler{store, sessions, handleWebSetAdmin})
	http.Handle("/api/list", webHandler{store, sessions, handleWebList})
	http.Handle("/api/list-full", webHandler{store, sessions, handleWebListFull})

	http.Handle("/admin/", http.StripPrefix("/admin/", http.FileServer(http.Dir(staticDir))))

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/" {
			http.NotFound(w, r)
			return
		}
		http.Redirect(w, r, "/admin/", http.StatusTemporaryRedirect)
	})

	wl.Printf("web-api: listening on '%s'", listener.Addr())
	server := &http.Server{ReadTimeout: 60 * time.Second, WriteTimeout: 60 * time.Second}
	return server.Serve(tcpKeepAliveListener{listener})
}
开发者ID:whawty,项目名称:auth,代码行数:28,代码来源:web_api.go

示例3: loop

func (s *Server) loop(listener *net.TCPListener) {
	defer s.waitGroup.Done()
	log.Printf("[DEBUG] waiting for connections...")
	for {
		select {
		case <-s.ch:
			log.Printf("[DEBUG] stopping listening on %s", listener.Addr())
			_ = listener.Close()
			return
		default:
		}
		_ = listener.SetDeadline(time.Now().Add(s.Deadline))
		conn, err := listener.AcceptTCP()
		if nil != err {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Printf("[ERROR] error on loop: %s", err)
		}
		log.Printf("[DEBUG] connected to %s", conn.RemoteAddr())
		c := &connection{
			conn:          conn,
			protocol:      s.protocolCtor(conn),
			waitGroup:     s.waitGroup,
			deadline:      s.Deadline,
			readBuffSize:  s.ReadBuffSize,
			writeBuffSize: s.WriteBuffSize,
		}
		s.waitGroup.Add(1)
		go c.handle(s.ch)
	}
}
开发者ID:larixsource,项目名称:atto,代码行数:32,代码来源:server.go

示例4: Serve

func (self *Service) Serve(listener *net.TCPListener) {
	defer self.wg.Done()

	log.Println("initializing...")
	var err error
	self.repo, err = repository.Initialize(self.dataDir)
	log.Println("data directory: ", self.dataDir)
	if err != nil {
		log.Fatal(err)
	}

	for {
		select {
		case <-self.ch:
			log.Println("stopping listening on", listener.Addr())
			listener.Close()
			return
		default:
		}
		listener.SetDeadline(time.Now().Add(1e9))
		conn, err := listener.AcceptTCP()
		if nil != err {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Println(err)
		}
		self.wg.Add(1)
		go self.HandleConnection(conn)
	}
}
开发者ID:gitter-badger,项目名称:siberite,代码行数:31,代码来源:service.go

示例5: Serve

// Accept connections and spawn a goroutine to serve each one.  Stop listening
// if anything is received on the service's channel.
func (self *Service) Serve(listener *net.TCPListener) {
	defer self.waitGroup.Done()
	for {
		select {
		case <-self.done:
			log.Println("Stopping listening on", listener.Addr())
			listener.Close()
			return
		default:
		}

		listener.SetDeadline(time.Now().Add(1e9))
		conn, err := listener.AcceptTCP()
		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Println(err)
		}

		log.Println(conn.RemoteAddr(), "connected")

		connection := NewConnection(conn, make(chan []byte))
		self.dataMap[connection.Id] = connection
		self.waitGroup.Add(1)
		go self.serve(connection)
	}
}
开发者ID:voxadam,项目名称:cascades-sockets,代码行数:30,代码来源:service.go

示例6: Start

func (this *Server) Start(listener *net.TCPListener) {
	log.Printf("Start listen on %v", listener.Addr())
	this.waitGroup.Add(1)
	defer func() {
		listener.Close()
		this.waitGroup.Done()
	}()

	for {
		select {
		case <-this.exitCh:
			log.Printf("Stop listen on %v", listener.Addr())
			return
		default:
		}

		listener.SetDeadline(time.Now().Add(this.acceptTimeout))
		conn, err := listener.AcceptTCP()
		if err != nil {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				// log.Printf("Accept timeout: %v", opErr)
				continue
			}
			log.Printf("Accept error: %v", err)
			continue
		}

		log.Printf("Accept: %v", conn.RemoteAddr())
		go this.handleClientConn(conn)
	}
}
开发者ID:ningye,项目名称:gotcp,代码行数:31,代码来源:server.go

示例7: New

func New(id circuit.WorkerID, bindAddr string, host string) *Transport {

	// Bind
	var l *net.TCPListener
	if strings.Index(bindAddr, ":") < 0 {
		bindAddr = bindAddr + ":0"
	}
	l_, err := net.Listen("tcp", bindAddr)
	if err != nil {
		panic(err)
	}

	// Build transport structure
	l = l_.(*net.TCPListener)
	t := &Transport{
		listener:   l,
		addrtabl:   makeAddrTabl(),
		pipelining: DefaultPipelining,
		remote:     make(map[circuit.WorkerID]*link),
		ach:        make(chan *conn),
	}

	// Resolve self address
	laddr := l.Addr().(*net.TCPAddr)
	t.self, err = NewAddr(id, os.Getpid(), fmt.Sprintf("%s:%d", host, laddr.Port))
	if err != nil {
		panic(err)
	}

	// This LocalAddr might be useless for connect purposes (e.g. 0.0.0.0). Consider self instead.
	t.bind = t.addrtabl.Normalize(&Addr{ID: id, PID: os.Getpid(), Addr: laddr})

	go t.loop()
	return t
}
开发者ID:rrudduck,项目名称:golang-stuff,代码行数:35,代码来源:transport.go

示例8: AcceptTCP

// Accept accepts connections on the listener and serves requests
// for each incoming connection.  Accept blocks; the caller typically
// invokes it in a go statement.
func (server *Server) AcceptTCP(lis *net.TCPListener, i int) {
	var (
		conn *net.TCPConn
		err  error
	)
	for {
		log.Debug("server: accept round: %d", i)
		if conn, err = lis.AcceptTCP(); err != nil {
			// if listener close then return
			log.Error("listener.Accept(\"%s\") error(%v)", lis.Addr().String(), err)
			return
		}
		if err = conn.SetKeepAlive(Conf.TCPKeepalive); err != nil {
			log.Error("conn.SetKeepAlive() error(%v)", err)
			return
		}
		if err = conn.SetReadBuffer(Conf.TCPSndbuf); err != nil {
			log.Error("conn.SetReadBuffer() error(%v)", err)
			return
		}
		if err = conn.SetWriteBuffer(Conf.TCPRcvbuf); err != nil {
			log.Error("conn.SetWriteBuffer() error(%v)", err)
			return
		}
		go server.serveConn(conn, i)
		if i++; i == maxInt {
			i = 0
		}
	}
}
开发者ID:xingskycn,项目名称:goim,代码行数:33,代码来源:server.go

示例9: newServer

func newServer(s *state.State, lis *net.TCPListener, cfg ServerConfig) (_ *Server, err error) {
	logger.Infof("listening on %q", lis.Addr())
	srv := &Server{
		state:     s,
		statePool: state.NewStatePool(s),
		addr:      lis.Addr().(*net.TCPAddr), // cannot fail
		tag:       cfg.Tag,
		dataDir:   cfg.DataDir,
		logDir:    cfg.LogDir,
		limiter:   utils.NewLimiter(loginRateLimit),
		validator: cfg.Validator,
		adminApiFactories: map[int]adminApiFactory{
			0: newAdminApiV0,
			1: newAdminApiV1,
			2: newAdminApiV2,
		},
	}
	srv.authCtxt = newAuthContext(srv)
	tlsCert, err := tls.X509KeyPair(cfg.Cert, cfg.Key)
	if err != nil {
		return nil, err
	}
	// TODO(rog) check that *srvRoot is a valid type for using
	// as an RPC server.
	tlsConfig := tls.Config{
		Certificates: []tls.Certificate{tlsCert},
	}
	changeCertListener := newChangeCertListener(lis, cfg.CertChanged, tlsConfig)
	go srv.run(changeCertListener)
	return srv, nil
}
开发者ID:snailwalker,项目名称:juju,代码行数:31,代码来源:apiserver.go

示例10: FreePorts

// FreePorts returns maximum n tcp ports available to use.
func FreePorts(n int, matchFunc func(int) bool) (ports []int, err error) {
	if n > 50000 {
		return nil, fmt.Errorf("too many ports requested (%d)", n)
	}
	for len(ports) < n {
		var addr *net.TCPAddr
		addr, err = net.ResolveTCPAddr("tcp", "localhost:0")
		if err != nil {
			break
		}
		var l *net.TCPListener
		l, err = net.ListenTCP("tcp", addr)
		if err != nil {
			break
		}
		port := l.Addr().(*net.TCPAddr).Port
		l.Close()

		if matchFunc == nil {
			ports = append(ports, port)
			continue
		}
		if matchFunc(port) {
			ports = append(ports, port)
		}
	}
	return
}
开发者ID:gyuho,项目名称:learn,代码行数:29,代码来源:15_free_ports.go

示例11: serve

func (tcp *Tcp) serve(listeningPoint *net.TCPListener) {
	log.Info("Begin serving TCP on address " + listeningPoint.Addr().String())

	for {
		baseConn, err := listeningPoint.Accept()
		if err != nil {
			log.Severe("Failed to accept TCP conn on address " + listeningPoint.Addr().String() + "; " + err.Error())
			continue
		}

		conn := NewConn(baseConn, tcp.output)
		log.Debug("Accepted new TCP conn %p from %s on address %s", &conn, conn.baseConn.RemoteAddr(), conn.baseConn.LocalAddr())
		tcp.connTable.Notify(baseConn.RemoteAddr().String(), conn)
	}
}
开发者ID:hinike,项目名称:gossip,代码行数:15,代码来源:transport_tcp.go

示例12: accept

/* Wait for and accept a client.  wg.Done() will be called when l is closed or
an error occurs (and the goroutine terminates). */
func accept(l *net.TCPListener, wg sync.WaitGroup) {
	defer wg.Done()
	for {
		/* Get a connection */
		c, err := l.AcceptTCP()
		/* Notify listener and die on error */
		if err != nil {
			log.Printf("Ceasing to listen on %v: %v", l.Addr(),
				err)
			return
		}
		/* Handle client */
		go handle(c)
	}
}
开发者ID:kelixin,项目名称:sshbf,代码行数:17,代码来源:listener.go

示例13: NewTcpAcceptor

func NewTcpAcceptor(strAddr string) (*TcpAcceptor, error) {
	var err error
	var listener *net.TCPListener
	var tcpAddr *net.TCPAddr
	if tcpAddr, err = net.ResolveTCPAddr("tcp", strAddr); err == nil {
		listener, err = net.ListenTCP("tcp", tcpAddr)
	}
	if err == nil {
		a := TcpAcceptor{}
		a.listener = listener
		addr := listener.Addr().String()
		a.endPoint, _ = NewTcpEndPoint(addr)
		return &a, nil
	} else {
		return nil, err
	}
}
开发者ID:jddixon,项目名称:xlTransport_go,代码行数:17,代码来源:tcp_acceptor.go

示例14: listenTCP

func listenTCP(host, port string) (err error) {
	var listener *net.TCPListener
	// Automatically assign open port
	address, err := net.ResolveTCPAddr("tcp", net.JoinHostPort(host, port))
	if err != nil {
		log.WithField("error", err).Fatal("Unable to resolve tcp address")
		return
	}
	listener, err = net.ListenTCP("tcp", address)
	if err != nil {
		log.WithField("error", err).Fatal("Unable to bind to tcp on localhost")
		return
	}
	log.WithField("address", listener.Addr()).Info("Listening")
	defer listener.Close()
	serve(listener)
	return
}
开发者ID:the-control-group,项目名称:nats-publisher,代码行数:18,代码来源:main.go

示例15: Run

func (this *Server) Run(listener *net.TCPListener) {
	defer func() {
		listener.Close()
	}()

	//go this.dealSpamConn()
	log.Infof("Starting comet server on: %s", listener.Addr().String())
	if err := storage.Instance.AddComet(this.Name); err != nil {
		log.Errorf("failed to add comet to Redis: %s", err.Error())
	}

	// keep the data of this node not expired on redis
	this.startRefreshRoutine()
	this.startWorkers()

	for {
		select {
		case <-this.ctrl:
			log.Infof("ask me to quit")
			this.stopWorkers()
			this.stopRefreshRoutine()
			return
		default:
		}

		listener.SetDeadline(time.Now().Add(this.acceptTimeout * time.Second))
		conn, err := listener.AcceptTCP()
		if err != nil {
			if e, ok := err.(*net.OpError); ok && e.Timeout() {
				continue
			}
			log.Errorf("accept failed: %v\n", err)
			continue
		}
		/*
			// first packet must sent by client in specified seconds
			if err = conn.SetReadDeadline(time.Now().Add(20)); err != nil {
				glog.Errorf("conn.SetReadDeadLine() error(%v)", err)
				conn.Close()
				continue
			}*/
		go this.handleConnection(conn)
	}
}
开发者ID:houcy,项目名称:push,代码行数:44,代码来源:server.go


注:本文中的net.TCPListener.Addr方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。