Clash.Meta/listener/http/server.go

58 lines
929 B
Go
Raw Normal View History

2018-06-14 01:00:58 +08:00
package http
2018-06-10 22:50:03 +08:00
import (
"net"
"time"
2018-06-10 22:50:03 +08:00
"github.com/Dreamacro/clash/common/cache"
2021-06-13 17:23:10 +08:00
C "github.com/Dreamacro/clash/constant"
2018-06-10 22:50:03 +08:00
)
2021-06-13 17:23:10 +08:00
type Listener struct {
listener net.Listener
closed bool
}
2021-06-13 17:23:10 +08:00
func New(addr string, in chan<- C.ConnContext) (*Listener, error) {
2021-06-15 17:13:40 +08:00
return NewWithAuthenticate(addr, in, true)
}
func NewWithAuthenticate(addr string, in chan<- C.ConnContext, authenticate bool) (*Listener, error) {
2018-07-15 22:23:20 +08:00
l, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
2018-07-15 22:23:20 +08:00
}
2021-06-15 17:13:40 +08:00
var c *cache.Cache
if authenticate {
c = cache.New(time.Second * 30)
}
hl := &Listener{
listener: l,
}
2018-07-15 22:23:20 +08:00
go func() {
2018-08-11 22:51:30 +08:00
for {
2021-06-15 17:13:40 +08:00
conn, err := hl.listener.Accept()
2018-08-11 22:51:30 +08:00
if err != nil {
if hl.closed {
2018-08-11 22:51:30 +08:00
break
}
continue
}
2021-06-15 17:13:40 +08:00
go HandleConn(conn, in, c)
2018-08-11 22:51:30 +08:00
}
2018-07-15 22:23:20 +08:00
}()
return hl, nil
}
2021-06-13 17:23:10 +08:00
func (l *Listener) Close() {
l.closed = true
l.listener.Close()
}
2018-07-15 22:23:20 +08:00
2021-06-13 17:23:10 +08:00
func (l *Listener) Address() string {
return l.listener.Addr().String()
2018-06-10 22:50:03 +08:00
}