本文整理汇总了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
}
示例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)
}
}
示例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()
}
}
示例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)
}
}()
}
}
示例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
}
}
}
}
示例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: 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()
}
}
示例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")
}
示例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()
}
}
示例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))
}
}
}
}
}
示例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
}
示例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()
}
示例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.")
}
}
}
示例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
}
示例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)
}
}