本文整理汇总了Golang中net.Listener类的典型用法代码示例。如果您正苦于以下问题:Golang Listener类的具体用法?Golang Listener怎么用?Golang Listener使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Listener类的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
}
示例2: 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))
}
}
}
}
}
示例3: TestStateTransitionActiveIdleClosed
// Test state transitions from new->active->-idle->closed using an actual
// network connection and make sure the waitgroup count is correct at the end.
func TestStateTransitionActiveIdleClosed(t *testing.T) {
var (
listener net.Listener
exitchan chan error
)
keyFile, err1 := helpers.NewTempFile(helpers.Key)
certFile, err2 := helpers.NewTempFile(helpers.Cert)
defer keyFile.Unlink()
defer certFile.Unlink()
if err1 != nil || err2 != nil {
t.Fatal("Failed to create temporary files", err1, err2)
}
for _, withTLS := range []bool{false, true} {
server := NewServer()
wg := helpers.NewWaitGroup()
statechanged := make(chan http.ConnState)
server.wg = wg
if withTLS {
listener, exitchan = startTLSServer(t, server, certFile.Name(), keyFile.Name(), statechanged)
} else {
listener, exitchan = startServer(t, server, statechanged)
}
client := newClient(listener.Addr(), withTLS)
client.Run()
// wait for client to connect, but don't let it send the request
if err := <-client.connected; err != nil {
t.Fatal("Client failed to connect to server", err)
}
client.sendrequest <- true
waitForState(t, statechanged, http.StateActive, "Client failed to reach active state")
rr := <-client.response
if rr.err != nil {
t.Fatalf("tls=%t unexpected error from client %s", withTLS, rr.err)
}
waitForState(t, statechanged, http.StateIdle, "Client failed to reach idle state")
// client is now in an idle state
close(client.sendrequest)
<-client.closed
waitForState(t, statechanged, http.StateClosed, "Client failed to reach closed state")
server.Close()
waiting := <-wg.WaitCalled
if waiting != 0 {
t.Errorf("Waitcount should be zero, got %d", waiting)
}
if err := <-exitchan; err != nil {
t.Error("Unexpected error during shutdown", err)
}
}
}
示例4: Serve
func (srv *Server) Serve(l net.Listener) error {
defer l.Close()
var tempDelay time.Duration
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("smtp: 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
}
go c.serve()
}
}
示例5: 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)
}
}()
}
}
示例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))
}()
}
}
示例7: ListenAndServe
// ListenAndServe listens on l, accepts network connections, and
// handles requests according to the doozer protocol.
func ListenAndServe(l net.Listener, canWrite chan bool, st *store.Store, p consensus.Proposer, rwsk, rosk string, self string) {
var w bool
for {
c, err := l.Accept()
if err != nil {
if err == syscall.EINVAL {
break
}
if e, ok := err.(*net.OpError); ok && !e.Temporary() {
break
}
log.Println(err)
continue
}
// has this server become writable?
select {
case w = <-canWrite:
canWrite = nil
default:
}
go serve(c, st, p, w, rwsk, rosk, self)
}
}
示例8: serve
func serve(listener net.Listener) {
certificate, err := tls.LoadX509KeyPair("server.crt", "server.key")
if err != nil {
panic(err)
}
for {
c, err := listener.Accept()
if err != nil {
log.Printf("accept: %s", err)
}
tlsConn := tls.Server(c, &tls.Config{
Certificates: []tls.Certificate{certificate},
})
if err := tlsConn.Handshake(); err != nil {
log.Printf("tls: %s", err)
}
go func() {
io.Copy(os.Stdout, tlsConn)
c.Close()
}()
go func() {
io.Copy(tlsConn, os.Stdin)
c.Close()
}()
}
}
示例9: serve
// serve connections on this listener until it is closed.
func (s *Server) serve(ln net.Listener) {
for {
conn, err := ln.Accept()
if err != nil {
if !s.isClosing() {
log.Error(err)
}
return
}
s.mu.Lock()
s.conns[conn] = struct{}{}
s.mu.Unlock()
go func() {
defer func() {
s.mu.Lock()
delete(s.conns, conn)
s.mu.Unlock()
conn.Close()
}()
if err := s.serveConn(conn); err != nil {
if err != io.EOF && !s.isClosing() {
log.Error(err)
}
}
}()
}
}
示例10: httpServer
func httpServer(listener net.Listener) {
var err error
templates, err = template.ParseGlob(fmt.Sprintf("%s/*.html", *templateDir))
if err != nil {
log.Printf("ERROR: %s", err.Error())
}
log.Printf("HTTP: listening on %s", listener.Addr().String())
handler := http.NewServeMux()
handler.HandleFunc("/ping", pingHandler)
handler.HandleFunc("/", indexHandler)
handler.HandleFunc("/nodes", nodesHandler)
handler.HandleFunc("/topic/", topicHandler)
handler.HandleFunc("/delete_topic", deleteTopicHandler)
handler.HandleFunc("/delete_channel", deleteChannelHandler)
handler.HandleFunc("/empty_channel", emptyChannelHandler)
server := &http.Server{
Handler: handler,
}
err = server.Serve(listener)
// theres no direct way to detect this error because it is not exposed
if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
log.Printf("ERROR: http.Serve() - %s", err.Error())
}
log.Printf("HTTP: closing %s", listener.Addr().String())
}
示例11: transponder
func transponder(t *testing.T, ln net.Listener, done chan<- int) {
defer func() { done <- 1 }()
c, err := ln.Accept()
if err != nil {
t.Errorf("net.Listener.Accept failed: %v", err)
return
}
c.LocalAddr()
c.RemoteAddr()
c.SetDeadline(time.Now().Add(100 * time.Millisecond))
c.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
c.SetWriteDeadline(time.Now().Add(100 * time.Millisecond))
defer c.Close()
b := make([]byte, 128)
n, err := c.Read(b)
if err != nil {
t.Errorf("net.Conn.Read failed: %v", err)
return
}
if _, err := c.Write(b[:n]); err != nil {
t.Errorf("net.Conn.Write failed: %v", err)
return
}
}
示例12: acceptConnections
func (cl *Client) acceptConnections(l net.Listener, utp bool) {
for {
cl.waitAccept()
conn, err := l.Accept()
conn = pproffd.WrapNetConn(conn)
if cl.closed.IsSet() {
if conn != nil {
conn.Close()
}
return
}
if err != nil {
log.Print(err)
// I think something harsher should happen here? Our accept
// routine just fucked off.
return
}
if utp {
acceptUTP.Add(1)
} else {
acceptTCP.Add(1)
}
cl.mu.RLock()
reject := cl.badPeerIPPort(
missinggo.AddrIP(conn.RemoteAddr()),
missinggo.AddrPort(conn.RemoteAddr()))
cl.mu.RUnlock()
if reject {
acceptReject.Add(1)
conn.Close()
continue
}
go cl.incomingConnection(conn, utp)
}
}
示例13: Listen
func (proc *requestProcessor) Listen(l net.Listener) {
config := newConfig(proc.server)
timeout := time.Duration(0) // how long to sleep on accept failure
for {
rw, err := l.Accept()
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
if timeout == 0 {
timeout = 5 * time.Millisecond
} else {
timeout *= 2
}
if max := 5 * time.Second; timeout > max {
timeout = max
}
log.Printf("stomp: Accept error: %v; retrying in %v", err, timeout)
time.Sleep(timeout)
continue
}
return
}
timeout = 0
// TODO: need to pass Server to connection so it has access to
// configuration parameters.
_ = client.NewConn(config, rw, proc.ch)
}
// This is no longer required for go 1.1
panic("not reached")
}
示例14: Serve
// server accepts incoming connections
func (s *ServerState) Serve(ln net.Listener) {
// Start sending worker updates at 1Hz
go s.sendWorkState(1)
// Start up our auto discover server
var a *discoveryServer
addr := ln.Addr()
if taddr, ok := addr.(*net.TCPAddr); ok {
var err error
a, err = newDiscoveryServer(taddr.Port)
if err != nil {
log.Print("Error starting auto-discovery", err)
return
}
defer a.stop()
}
// Incoming connections
for {
DebugPrint("Server accepting...")
conn, err := ln.Accept()
if err != nil {
log.Print(err)
continue
}
// Turn into a message conn
mc := NewMessageConn(conn, time.Duration(10)*time.Second)
// Spin off thread to handle the new connection
go s.handleConnection(mc)
}
}
示例15: 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)
}
}