Stop server on context cancellation

This commit is contained in:
Elara 2023-03-28 13:25:54 -07:00
parent 883d32209c
commit b2ffc744b5

View File

@ -30,18 +30,24 @@ func NewWithOptions(handler drpc.Handler, opts drpcserver.Options) *Server {
// Serve listens on the given listener and handles all multiplexed
// streams.
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
for {
conn, err := ln.Accept()
if err != nil {
return err
}
connCh := make(chan net.Conn, 2)
errCh := make(chan error, 2)
go connChannel(ln, connCh, errCh)
for {
select {
case conn := <-connCh:
sess, err := yamux.Server(conn, nil)
if err != nil {
return err
}
go s.handleSession(ctx, sess)
case err := <-errCh:
return err
case <-ctx.Done():
return nil
}
}
}
@ -62,3 +68,14 @@ func (s *Server) handleSession(ctx context.Context, sess *yamux.Session) {
func (s *Server) ServeOne(ctx context.Context, conn io.ReadWriteCloser) error {
return s.srv.ServeOne(ctx, conn)
}
func connChannel(ln net.Listener, connCh chan net.Conn, errCh chan error) {
for {
conn, err := ln.Accept()
if err != nil {
errCh <- err
continue
}
connCh <- conn
}
}