serve_channel.go 1.2 KB

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