frp/utils/net/listener.go

70 lines
1.4 KiB
Go
Raw Normal View History

2017-06-08 19:33:57 +02:00
// Copyright 2017 fatedier, fatedier@gmail.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package net
import (
2017-06-25 21:02:33 +02:00
"fmt"
2017-06-08 19:33:57 +02:00
"net"
2017-06-25 21:02:33 +02:00
"sync"
2017-06-08 19:33:57 +02:00
2018-05-07 20:13:30 +02:00
"github.com/fatedier/golib/errors"
2017-06-08 19:33:57 +02:00
)
2017-06-25 21:02:33 +02:00
// Custom listener
type CustomListener struct {
2019-10-12 14:13:12 +02:00
acceptCh chan net.Conn
closed bool
mu sync.Mutex
2017-06-25 21:02:33 +02:00
}
func NewCustomListener() *CustomListener {
return &CustomListener{
2019-10-12 14:13:12 +02:00
acceptCh: make(chan net.Conn, 64),
2017-06-25 21:02:33 +02:00
}
}
2019-10-12 14:13:12 +02:00
func (l *CustomListener) Accept() (net.Conn, error) {
conn, ok := <-l.acceptCh
2017-06-25 21:02:33 +02:00
if !ok {
return nil, fmt.Errorf("listener closed")
}
return conn, nil
}
2019-10-12 14:13:12 +02:00
func (l *CustomListener) PutConn(conn net.Conn) error {
2017-06-25 21:02:33 +02:00
err := errors.PanicToError(func() {
select {
2019-10-12 14:13:12 +02:00
case l.acceptCh <- conn:
2017-06-25 21:02:33 +02:00
default:
conn.Close()
}
})
return err
}
func (l *CustomListener) Close() error {
l.mu.Lock()
defer l.mu.Unlock()
if !l.closed {
2019-10-12 14:13:12 +02:00
close(l.acceptCh)
2017-06-25 21:02:33 +02:00
l.closed = true
}
return nil
}
func (l *CustomListener) Addr() net.Addr {
return (*net.TCPAddr)(nil)
}