當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。