serve_channel.go 1.1 KB

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