github.com/Night-mk/quorum@v21.1.0+incompatible/raft/listener.go (about) 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 15 package raft 16 17 import ( 18 "errors" 19 "net" 20 "time" 21 ) 22 23 // stoppableListener sets TCP keep-alive timeouts on accepted 24 // connections and waits on stopc message 25 type stoppableListener struct { 26 *net.TCPListener 27 stopc <-chan struct{} 28 } 29 30 func newStoppableListener(addr string, stopc <-chan struct{}) (*stoppableListener, error) { 31 ln, err := net.Listen("tcp", addr) 32 if err != nil { 33 return nil, err 34 } 35 return &stoppableListener{ln.(*net.TCPListener), stopc}, nil 36 } 37 38 func (ln stoppableListener) Accept() (c net.Conn, err error) { 39 connc := make(chan *net.TCPConn, 1) 40 errc := make(chan error, 1) 41 go func() { 42 tc, err := ln.AcceptTCP() 43 if err != nil { 44 errc <- err 45 return 46 } 47 connc <- tc 48 }() 49 select { 50 case <-ln.stopc: 51 return nil, errors.New("server stopped") 52 case err := <-errc: 53 return nil, err 54 case tc := <-connc: 55 tc.SetKeepAlive(true) 56 tc.SetKeepAlivePeriod(3 * time.Minute) 57 return tc, nil 58 } 59 }