github.com/polarismesh/polaris@v1.17.8/common/conn/keepalive/keepalive.go (about) 1 /** 2 * Tencent is pleased to support the open source community by making Polaris available. 3 * 4 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. 5 * 6 * Licensed under the BSD 3-Clause License (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * https://opensource.org/licenses/BSD-3-Clause 11 * 12 * Unless required by applicable law or agreed to in writing, software distributed 13 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 * specific language governing permissions and limitations under the License. 16 */ 17 18 package keepalive 19 20 import ( 21 "net" 22 "time" 23 ) 24 25 var DefaultAlivePeriodTime = 3 * time.Minute 26 27 // tcpKeepAliveListener sets TCP keep-alive timeouts on accepted 28 // connections. It's used by ListenAndServe and ListenAndServeTLS so 29 // dead TCP connections (e.g. closing laptop mid-download) eventually 30 // go away. 31 // 来自net/http 32 type TcpKeepAliveListener struct { 33 periodTime time.Duration 34 *net.TCPListener 35 } 36 37 func NewTcpKeepAliveListener(periodTime time.Duration, ln *net.TCPListener) net.Listener { 38 return &TcpKeepAliveListener{ 39 periodTime: periodTime, 40 TCPListener: ln, 41 } 42 } 43 44 // Accept 来自于net/http 45 func (ln TcpKeepAliveListener) Accept() (net.Conn, error) { 46 tc, err := ln.AcceptTCP() 47 if err != nil { 48 return nil, err 49 } 50 err = tc.SetKeepAlive(true) 51 if err != nil { 52 return nil, err 53 } 54 55 err = tc.SetKeepAlivePeriod(ln.periodTime) 56 if err != nil { 57 return nil, err 58 } 59 60 return tc, nil 61 }