serve_channel.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package proxy
  2. import (
  3. "fmt"
  4. "log"
  5. "net"
  6. "runtime/debug"
  7. )
  8. type ServerChannel struct {
  9. ip string
  10. port int
  11. Listener *net.Listener
  12. errAcceptHandler func(err error)
  13. }
  14. func NewServerChannel(ip string, port int) ServerChannel {
  15. return ServerChannel{
  16. ip: ip,
  17. port: port,
  18. errAcceptHandler: func(err error) {
  19. fmt.Printf("accept error , ERR:%s", err)
  20. },
  21. }
  22. }
  23. func (sc *ServerChannel) ListenTCP(fn func(conn net.Conn)) (err error) {
  24. var l net.Listener
  25. l, err = net.Listen("tcp", fmt.Sprintf("%s:%d", sc.ip, sc.port))
  26. if err == nil {
  27. sc.Listener = &l
  28. go func() {
  29. defer func() {
  30. if e := recover(); e != nil {
  31. log.Printf("ListenTCP crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
  32. }
  33. }()
  34. for {
  35. var conn net.Conn
  36. conn, err = (*sc.Listener).Accept()
  37. if err == nil {
  38. go func() {
  39. defer func() {
  40. if e := recover(); e != nil {
  41. log.Printf("connection handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
  42. }
  43. }()
  44. fn(conn)
  45. }()
  46. } else {
  47. sc.errAcceptHandler(err)
  48. break
  49. }
  50. }
  51. }()
  52. }
  53. return
  54. }
  55. func (sc *ServerChannel) CloseListen() error {
  56. return (*sc.Listener).Close()
  57. }