12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package proxy
- import (
- "fmt"
- "net"
- "runtime/debug"
- )
- type ServerChannel struct {
- ip string
- port int
- Listener *net.Listener
- errAcceptHandler func(err error)
- }
- func NewServerChannel(ip string, port int) ServerChannel {
- return ServerChannel{
- ip: ip,
- port: port,
- errAcceptHandler: func(err error) {
- fmt.Printf("accept error , ERR:%s", err)
- },
- }
- }
- func (sc *ServerChannel) ListenTCP(fn func(conn net.Conn)) (err error) {
- var l net.Listener
- l, err = net.Listen("tcp", fmt.Sprintf("%s:%d", sc.ip, sc.port))
- if err == nil {
- sc.Listener = &l
- go func() {
- defer func() {
- if e := recover(); e != nil {
- logger.Sugar().Infof("ListenTCP crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
- }
- }()
- for {
- var conn net.Conn
- conn, err = (*sc.Listener).Accept()
- if err == nil {
- go func() {
- defer func() {
- if e := recover(); e != nil {
- logger.Sugar().Infof("connection handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
- }
- }()
- fn(conn)
- }()
- } else {
- sc.errAcceptHandler(err)
- break
- }
- }
- }()
- }
- return
- }
- func (sc *ServerChannel) CloseListen() error {
- return (*sc.Listener).Close()
- }
|