Skip to content

Commit

Permalink
support graceful shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
liujianping committed Jul 26, 2019
1 parent 0be2365 commit 606167b
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion tcpserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"log"
"net"
"sync"
)

//ConnectionHandler connection handler definition
Expand All @@ -14,6 +15,8 @@ type Server struct {
network string
address string
handler ConnectionHandler
closed chan bool
wgroup sync.WaitGroup
}

//Network option for listener
Expand Down Expand Up @@ -48,7 +51,9 @@ type ServerOpt func(*Server)

//NewServer create a new tcpserver
func NewServer(opts ...ServerOpt) *Server {
serv := &Server{}
serv := &Server{
closed: make(chan bool),
}
for _, opt := range opts {
opt(serv)
}
Expand All @@ -67,6 +72,9 @@ func (srv *Server) Serve(ctx context.Context) error {
select {
case <-ctx.Done():
return ctx.Err()
case <-srv.closed:
log.Println("tcpserver is closing ...")
return nil
default:
con, err := ln.Accept()
if err != nil {
Expand All @@ -77,11 +85,19 @@ func (srv *Server) Serve(ctx context.Context) error {
return err
}

srv.wgroup.Add(1)
go func() {
defer srv.wgroup.Done()
if err := srv.handler(ctx, con); err != nil {
log.Printf("connection %s handle failed: %s\n", con.RemoteAddr().String(), err)
}
}()
}
}
}

//Close tcpserver waiting all connections finished
func (srv *Server) Close() {
close(srv.closed)
srv.wgroup.Wait()
}

0 comments on commit 606167b

Please sign in to comment.