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


Golang Listener.Accept方法代码示例

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


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

示例1: listenAndServeScgi

func (s *Server) listenAndServeScgi(addr string) error {

	var l net.Listener
	var err error

	//if the path begins with a "/", assume it's a unix address
	if strings.HasPrefix(addr, "/") {
		l, err = net.Listen("unix", addr)
	} else {
		l, err = net.Listen("tcp", addr)
	}

	//save the listener so it can be closed
	s.l = l

	if err != nil {
		s.Logger.Println("SCGI listen error", err.Error())
		return err
	}

	for {
		fd, err := l.Accept()
		if err != nil {
			s.Logger.Println("SCGI accept error", err.Error())
			return err
		}
		go s.handleScgiRequest(fd)
	}
	return nil
}
开发者ID:puzhengwu,项目名称:goweb,代码行数:30,代码来源:scgi.go

示例2: Serve

// Serve starts a secure echo server on the given listener.
func Serve(l net.Listener) error {
	defer l.Close()
	pub, priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return err
	}

	for {
		rawConn, err := l.Accept()
		if err != nil {
			return err
		}
		conn := &Conn{rawConn: rawConn, pub: pub, priv: priv}
		go func(c *Conn) {
			defer c.Close()
			buf := make([]byte, 1024*32)
			n, err := c.Read(buf)
			if err != nil {
				fmt.Println(err)
			}
			got := string(buf[:n])
			log.Print(got)
			// echo the message
			n, err = c.Write([]byte(got))
			if err != nil {
				fmt.Println(err)
			}
		}(conn)
	}

}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:32,代码来源:main.go

示例3: Serve

func (srv *Server) Serve(l net.Listener) error {
	defer l.Close()
	var tempDelay time.Duration // how long to sleep on accept failure
	for {
		rw, e := l.Accept()
		if e != nil {
			if ne, ok := e.(net.Error); ok && ne.Temporary() {
				if tempDelay == 0 {
					tempDelay = 5 * time.Millisecond
				} else {
					tempDelay *= 2
				}
				if max := 1 * time.Second; tempDelay > max {
					tempDelay = max
				}
//				srv.logf("http: Accept error: %v; retrying in %v", e, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			return e
		}
		tempDelay = 0
		c, err := srv.newConn(rw)
		if err != nil {
			continue
		}
//		c.setState(c.rwc, StateNew) // before Serve can return
		go c.serve()
	}
}
开发者ID:lkj01010,项目名称:mygo01,代码行数:30,代码来源:server.go

示例4: acceptClientConnections

func (c *controller) acceptClientConnections(sock string, l net.Listener) {
	for {
		conn, err := l.Accept()
		if err != nil {
			if _, err1 := os.Stat(sock); os.IsNotExist(err1) {
				logrus.Debugf("Unix socket %s doesn't exist. cannot accept client connections", sock)
				return
			}
			logrus.Errorf("Error accepting connection %v", err)
			continue
		}
		go func() {
			defer conn.Close()

			err := c.processExternalKey(conn)
			ret := success
			if err != nil {
				ret = err.Error()
			}

			_, err = conn.Write([]byte(ret))
			if err != nil {
				logrus.Errorf("Error returning to the client %v", err)
			}
		}()
	}
}
开发者ID:Raphaeljunior,项目名称:docker,代码行数:27,代码来源:sandbox_externalkey_unix.go

示例5: server

func server(t *testing.T, listener net.Listener, connHandler ConnectionHandler, stopCh chan bool, acceptDelay time.Duration) {
	defer listener.Close()

	connCh := make(chan net.Conn, 0)
	errCh := make(chan error, 0)
	go func() {
		for {
			time.Sleep(acceptDelay)
			conn, err := listener.Accept()
			if err == nil {
				connCh <- conn
			} else {
				errCh <- err
			}
		}
	}()
AcceptLoop:
	for {
		select {
		case <-stopCh:
			break AcceptLoop
		case conn := <-connCh:
			go connHandler(t, conn)
		case err := <-errCh:
			if _, ok := <-stopCh; !ok {
				t.Error("Accept:", err.Error())
			} else {
				break AcceptLoop
			}
		}
	}
}
开发者ID:temoto,项目名称:heroshi,代码行数:32,代码来源:transport_test.go

示例6: runBackendInstance

func runBackendInstance(ln net.Listener, handler connHandler) {
	var tempDelay time.Duration // how long to sleep on accept failure
	for {
		conn, err := ln.Accept()
		if err != nil {
			if ne, ok := err.(net.Error); ok && ne.Temporary() {
				if tempDelay == 0 {
					tempDelay = 5 * time.Millisecond
				} else {
					tempDelay *= 2
				}
				if max := 1 * time.Second; tempDelay > max {
					tempDelay = max
				}
				fmt.Printf("http: Accept error: %v; retrying in %v\n", err, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			break
		}
		go func() {
			defer GinkgoRecover()
			handler(test_util.NewHttpConn(conn))
		}()
	}
}
开发者ID:sunatthegilddotcom,项目名称:gorouter,代码行数:26,代码来源:proxy_test.go

示例7: RunServer

func RunServer(cfg Config) {
	memoryStore := NewStore()

	var ln net.Listener
	var err error

	if cfg.TLSEnabled() {
		ln, err = tls.Listen("tcp", ":"+cfg.Port, cfg.TLSConfig())
	} else {
		ln, err = net.Listen("tcp", ":"+cfg.Port)
	}
	if err != nil {
		log.Println("Failed to start server:", err.Error())
	}

	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Println("Client failed to open new connection:", err.Error())
		}

		id, err := newUUID()
		if err != nil {
			log.Println("Failed to create unique ID for new client")
			conn.Close()
			continue
		}

		log.Printf("New connection opened clientId=%s", id)

		c := NewClient(id, conn, memoryStore)
		go c.Handle()
	}
}
开发者ID:bradylove,项目名称:mescal,代码行数:34,代码来源:main.go

示例8: Serve

// Serve accepts incoming connections on the Listener l, creating a
// new service thread for each.  The service threads read requests and
// then call srv.Handler to reply to them.
func (srv *Server) Serve(l net.Listener) error {
	defer l.Close()
	handler := srv.Handler
	if handler == nil {
		handler = DefaultServeMux
	}

	for {
		rw, e := l.Accept()
		if e != nil {
			if ne, ok := e.(net.Error); ok && ne.Temporary() {
				log.Printf("icap: Accept error: %v", e)
				continue
			}
			return e
		}
		if srv.ReadTimeout != 0 {
			rw.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
		}
		if srv.WriteTimeout != 0 {
			rw.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
		}
		c, err := newConn(rw, handler)
		if err != nil {
			continue
		}
		go c.serve()
	}
	panic("not reached")
}
开发者ID:dot-Sean,项目名称:go-icap,代码行数:33,代码来源:server.go

示例9: StartMockLivestatus

func (mockLive *MockLivestatus) StartMockLivestatus() {
	var listener net.Listener
	var err error
	switch mockLive.ConnectionType {
	case "tcp":
		listener, err = net.Listen("tcp", mockLive.LivestatusAddress)
	case "file":
		listener, err = net.Listen("unix", mockLive.LivestatusAddress)
	default:
		log.Panic("ConnectionType undefined")
		return
	}

	if err != nil {
		log.Panic(err)
	}

	isRunning := true
	for isRunning {
		conn, err := listener.Accept()
		if err != nil {
			//log.Println(err)
			continue
		}
		go mockLive.handle(conn)

		mutex.Lock()
		isRunning = mockLive.isRunning
		mutex.Unlock()
	}
}
开发者ID:Griesbacher,项目名称:nagflux,代码行数:31,代码来源:Connector_test.go

示例10: doAcceptTcpClients

func (this *TcpServer) doAcceptTcpClients(hServer net.Listener) {
	for {
		conn, err := hServer.Accept()
		if this.beNotifiedToShutDown {
			break
		}

		this.initClientWithConnection(conn)

		if err != nil {
			//回调accept失败
			if nil != this.delegate {
				_, implemented := this.delegate.(ITcpServerDelegate)
				if implemented {
					this.delegate.TcpServerAcceptClientError(this.getClientInfoMapClient(conn), err.Error())
					break
				}
			}
		} else {

			handlerThread := this.createHandlerThread(conn)
			this.addHandlerThreadToQueue(handlerThread)
			this.setClientInfoMapConnectionThread(conn, handlerThread)

			if nil != this.delegate {
				_, implemented := this.delegate.(ITcpServerDelegate)
				if implemented {
					this.delegate.TcpServerClientConnected(this.getClientInfoMapClient(conn))
				}
			}
		}
	}
}
开发者ID:ziyouchutuwenwu,项目名称:genTcpServer,代码行数:33,代码来源:TcpServerPrivate.go

示例11: Serve

// ListenAndServe services SPDY requests using the given listener.
// If the handler is nil, then http.DefaultServeMux is used.
func (srv *Server) Serve(l net.Listener) error {
	defer l.Close()
	handler := srv.Handler
	if handler == nil {
		handler = http.DefaultServeMux
	}
	for {
		fmt.Println("Spdy waiting for connections...")
		conn, err := l.Accept()
		fmt.Println("...Spdy accepted connection... %v->%v", conn.RemoteAddr(), conn.LocalAddr())
		if err != nil {
			return err
		}
		go func(c net.Conn) {
			// Echo all incoming data.
			fmt.Println("echoing data...")
			bb := new(bytes.Buffer)
			io.Copy(bb, c)
			// Shut down the connection.
			fmt.Println("spdyrequest: %s", bb.String())
			fmt.Println("closing conn...")
			c.Close()
		}(conn)
		// s, err := newSession(c, handler)
		// if err != nil {
		// return err
		// }
		// go s.serve()
	}
	/*
	 */
	return nil
}
开发者ID:sherwinyu,项目名称:cs490spdy,代码行数:35,代码来源:server.go

示例12: dataAccept

func dataAccept(l net.Listener, f *FtpConn) {

	conn, err := l.Accept()
	if err != nil {
		log.Fatal(err)
	}

	switch <-f.pasvChan {
	case 1: //send
		f.getFileList(conn)
		f.pasvChan <- -1
	case 2: //store
		fout, err := os.Create(filepath.Join(getRealPath(f.wd), f.fileName))
		defer fout.Close()
		if err != nil {
			log.Println(err)
			f.pasvChan <- 0
			return
		}
		io.Copy(fout, conn)
		f.pasvChan <- -2
	case 3: //retr
		fout, err := os.Open(filepath.Join(getRealPath(f.wd), f.fileName))
		defer fout.Close()
		if err != nil {
			log.Println(err)
			f.pasvChan <- 0
			return
		}
		io.Copy(conn, fout)
		f.pasvChan <- -3
	}
	conn.Close()
	l.Close()
}
开发者ID:lpgo,项目名称:ftp,代码行数:35,代码来源:server.go

示例13: Serve

// Serve starts a secure echo server on the given listener. Sending an empty
// message will quit the server.
func Serve(l net.Listener) error {

	for {
		conn, err := l.Accept()
		if err != nil {
			return err
		}
		defer conn.Close()

		pub, priv, err := box.GenerateKey(rand.Reader)
		if err != nil {
			return err
		}

		peer, err := exchangeKeys(conn, pub)
		if err != nil {
			return err
		}
		secure := NewSecureConn(conn, priv, peer)

		// If nothing is copied then the server will end. This allows the client to
		// send an empty message to kill the server.
		if n, err := io.Copy(secure, secure); n == 0 {
			if err != nil {
				return err
			}
			return fmt.Errorf("Server ending.")
		}
	}
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:32,代码来源:server.go

示例14: Chan

/*
	Yields all accepted connections to the net.Listener on the returned Channel.
*/
func Chan(ln net.Listener, backlog int) *Netchan {
	c := &Netchan{}
	c.Accept = make(chan net.Conn, backlog)
	c.Quit = make(chan bool, 1)
	c.Listener = ln

	go func() {
		select {
		case <-c.Quit:
			close(c.Accept)

			if err := ln.Close(); err != nil {
				panic(err)
			}

			c.Quit <- true
		}
	}()

	go func() {
		for {
			conn, err := ln.Accept()

			// An error means that the listener was closed, or another event
			// happened where we can't continue listening for connections.
			if err != nil {
				return
			}

			c.Accept <- conn
		}
	}()

	return c
}
开发者ID:jmptrader,项目名称:netchan-2,代码行数:38,代码来源:netchan.go

示例15: Serve

// Serve handles connections from ln and multiplexes then across registered listener.
func (mux *Mux) Serve(ln net.Listener) error {
	mux.mu.Lock()
	mux.ln = ln
	mux.mu.Unlock()
	for {
		// Wait for the next connection.
		// If it returns a temporary error then simply retry.
		// If it returns any other error then exit immediately.
		conn, err := ln.Accept()
		if err, ok := err.(interface {
			Temporary() bool
		}); ok && err.Temporary() {
			continue
		}
		if err != nil {
			// Wait for all connections to be demux
			mux.wg.Wait()
			for _, ln := range mux.m {
				close(ln.c)
			}
			return err
		}

		// Demux in a goroutine to
		mux.wg.Add(1)
		go mux.handleConn(conn)
	}
}
开发者ID:daneroo,项目名称:go-ted1k,代码行数:29,代码来源:mux.go


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