1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- package proxy
- import (
- "fmt"
- "log"
- "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 {
- log.Printf("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 {
- log.Printf("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()
- }
|