12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- 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
- }
|