listener.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "errors"
  17. "net"
  18. "time"
  19. )
  20. // stoppableListener sets TCP keep-alive timeouts on accepted
  21. // connections and waits on stopc message
  22. type stoppableListener struct {
  23. *net.TCPListener
  24. stopc <-chan struct{}
  25. }
  26. func newStoppableListener(addr string, stopc <-chan struct{}) (*stoppableListener, error) {
  27. ln, err := net.Listen("tcp", addr)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return &stoppableListener{ln.(*net.TCPListener), stopc}, nil
  32. }
  33. func (ln stoppableListener) Accept() (c net.Conn, err error) {
  34. connc := make(chan *net.TCPConn, 1)
  35. errc := make(chan error, 1)
  36. go func() {
  37. tc, err := ln.AcceptTCP()
  38. if err != nil {
  39. errc <- err
  40. return
  41. }
  42. connc <- tc
  43. }()
  44. select {
  45. case <-ln.stopc:
  46. return nil, errors.New("server stopped")
  47. case err := <-errc:
  48. return nil, err
  49. case tc := <-connc:
  50. tc.SetKeepAlive(true)
  51. tc.SetKeepAlivePeriod(3 * time.Minute)
  52. return tc, nil
  53. }
  54. }