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


Golang Listener.Close方法代码示例

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


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

示例1: Serve

func Serve(log *logging.Logger, addr string, ssl *ini.File) {
	var cmd []byte
	var ln net.Listener

	if ssl != nil {
		certificate := ssl.Section("ssl").Key("certificate").String()
		key := ssl.Section("ssl").Key("key").String()

		ln = tlsServe(log, addr, certificate, key)
		log.Debug("Opened SSL socket")
	} else {
		ln = plainServe(log, addr)
		log.Debug("Opened plain socket")
	}
	defer ln.Close()

	for {
		conn, err := ln.Accept()
		buff := bufio.NewReader(conn)

		if err != nil {
			// handle error
			log.Error("Error: %v\n", err)
		}
		log.Debug("Connection from " + conn.RemoteAddr().String() + " accepted")

		cmd, err = buff.ReadBytes('\n')
		log.Debug("Remote data readed")
		Parse(log, cmd, conn)
		conn.Close()
	}
}
开发者ID:mementobackup,项目名称:client,代码行数:32,代码来源:serve.go

示例2: 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

示例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: serveSingleCopy

func serveSingleCopy(name string, l net.Listener, dst io.Writer, src io.Reader) {
	defer l.Close()

	conn, err := l.Accept()
	if err != nil {
		log.Printf("'%s' accept error: %s", name, err)
		return
	}

	// Be sure to close the connection after we're done copying so
	// that an EOF will successfully be sent to the remote side
	defer conn.Close()

	// The connection is the destination/source that is nil
	if dst == nil {
		dst = conn
	} else {
		src = conn
	}

	written, err := io.Copy(dst, src)
	log.Printf("%d bytes written for '%s'", written, name)
	if err != nil {
		log.Printf("'%s' copy error: %s", name, err)
	}
}
开发者ID:henrikhodne,项目名称:packer,代码行数:26,代码来源:communicator.go

示例5: handleInterrupt

func (srv *Server) handleInterrupt(interrupt chan os.Signal, quitting chan struct{}, listener net.Listener) {
	for _ = range interrupt {
		if srv.Interrupted {
			srv.logf("already shutting down")
			continue
		}
		srv.logf("shutdown initiated")
		srv.Interrupted = true
		if srv.BeforeShutdown != nil {
			if !srv.BeforeShutdown() {
				srv.Interrupted = false
				continue
			}
		}

		close(quitting)
		srv.SetKeepAlivesEnabled(false)
		if err := listener.Close(); err != nil {
			srv.logf("[ERROR] %s", err)
		}

		if srv.ShutdownInitiated != nil {
			srv.ShutdownInitiated()
		}
	}
}
开发者ID:stellar,项目名称:bridge-server,代码行数:26,代码来源:graceful.go

示例6: 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

示例7: 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

示例8: Listen

// Start network server
func (s *Server) Listen() error {
	tlsConfig, err := crypto.GetServerTlsConfig()
	if err != nil {
		return err
	}

	var listener net.Listener
	if tlsConfig != nil {
		listener, err = tls.Listen("tcp", s.address, tlsConfig)
	} else {
		listener, err = net.Listen("tcp", s.address)
		log.Println("Warning: creating a non-TLS insecure server")
	}
	if err != nil {
		return err
	}

	defer listener.Close()

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

		s.newClient(conn)
	}

	return nil
}
开发者ID:emersion,项目名称:miko,代码行数:31,代码来源:server.go

示例9: loop

func (srv *Server) loop(l net.Listener) error {
	defer l.Close()
	var tempDelay time.Duration // how long to sleep on accept failure
	for {
		grw, 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
				}
				log.Errorf("rtmp: Accept error: %v; retrying in %v", e, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			return e
		}
		tempDelay = 0
		go serve(srv, grw)
	}
}
开发者ID:sichuanyl,项目名称:babylon,代码行数:25,代码来源:server.go

示例10: Serve

// Serve принимает входящее соединение и запускает в отдельном потоке его обработку.
func (srv *Server) Serve(l net.Listener) error {
	log.Printf("Listen %s...", srv.Addr)
	if srv.connections == nil {
		srv.connections = NewList() // инициализируем хранилище информации о соединениях
	}
	var tempDelay time.Duration // задержка до возврата ошибки
	for {
		conn, err := l.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
				}
				log.Printf("Accept error: %v; retrying in %v", err, tempDelay)
				time.Sleep(tempDelay)
				continue
			}
			l.Close()
			return err
		}
		tempDelay = 0
		go srv.servConn(conn) // запускаем обработку соединения
	}
}
开发者ID:XYZrd,项目名称:locator,代码行数:30,代码来源:server.go

示例11: serverMain

func serverMain() {
	var ln net.Listener
	var list_err error
	//fmt.Println("Starting server...")

	tcpAddr, err := net.ResolveTCPAddr("tcp", ":8080")
	if err != nil {
		log.Println(err)
	}

	for {
		ln, list_err = net.ListenTCP("tcp", tcpAddr)
		if list_err != nil {
			log.Println(list_err)
		} else {
			break
		}
	}
	defer ln.Close()
	for {
		// accept connection on port
		conn, con_err := ln.Accept()
		if con_err != nil {
			log.Println(con_err)
			continue
		}
		go handleConnection(conn)
	}
}
开发者ID:imran91,项目名称:CS733,代码行数:29,代码来源:server.go

示例12: Run

// Run accepts incoming `quiltctl` connections and responds to them.
func Run(conn db.Conn, listenAddr string) error {
	proto, addr, err := api.ParseListenAddress(listenAddr)
	if err != nil {
		return err
	}

	var sock net.Listener
	apiServer := server{conn}
	for {
		sock, err = net.Listen(proto, addr)

		if err == nil {
			break
		}
		log.WithError(err).Error("Failed to open socket.")

		time.Sleep(30 * time.Second)
	}

	// Cleanup the socket if we're interrupted.
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGHUP)
	go func(c chan os.Signal) {
		sig := <-c
		log.Printf("Caught signal %s: shutting down.\n", sig)
		sock.Close()
		os.Exit(0)
	}(sigc)

	s := grpc.NewServer()
	pb.RegisterAPIServer(s, apiServer)
	s.Serve(sock)

	return nil
}
开发者ID:NetSys,项目名称:quilt,代码行数:36,代码来源:server.go

示例13: run

func (w *Worker) run(listener net.Listener) {
	defer close(w.wait)
	defer listener.Close()
	server := &http.Server{Handler: http.HandlerFunc(w.handleRequest)}
	go server.Serve(listener)
	<-w.quit
}
开发者ID:JeremyOT,项目名称:gototo,代码行数:7,代码来源:httpworker.go

示例14: TestShutdownWaitsForJobCompletion

func TestShutdownWaitsForJobCompletion(t *testing.T) {
	var wg sync.WaitGroup
	name := "shutdown_worker"
	var listener net.Listener

	listener, _ = makeJobAssignServer(":1337", name, "")
	defer listener.Close()

	ranJob := false
	worker := NewWorker(name, func(job Job) ([]byte, error) {
		wg.Done()
		time.Sleep(time.Duration(10 * time.Millisecond))
		ranJob = true
		return []byte{}, nil
	})
	worker.sigtermHandler = getTestSigtermHandler()

	wg.Add(1)
	go worker.Listen("localhost", "1337")
	wg.Wait()
	worker.w.Shutdown()
	if !ranJob {
		t.Error("Didn't run job")
	}
}
开发者ID:Clever,项目名称:ARCHIVED-baseworker-go,代码行数:25,代码来源:worker_test.go

示例15: TestJobAssign

// TestJobAssign tests that the worker runs the JOB_FUNC if the server sends a 'JOB_ASSIGN' packet.
func TestJobAssign(t *testing.T) {

	name := "worker_name"
	workload := "the_workload"

	var channel chan error
	var listener net.Listener

	listener, channel = makeJobAssignServer(":1337", name, workload)
	defer listener.Close()

	worker := NewWorker(name, func(job Job) ([]byte, error) {
		if string(job.Data()) != workload {
			close(channel)
			t.Fatalf("expected workload of '%s', received '%s'", workload, string(job.Data()))
		}
		close(channel)
		return []byte{}, nil
	})
	go worker.Listen("localhost", "1337")

	for err := range channel {
		t.Fatal(err)
	}
	worker.w.Shutdown()
}
开发者ID:Clever,项目名称:gearcmd,代码行数:27,代码来源:worker_test.go


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