app-quitsocket.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package comm
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. type QuitCtx map[string]interface{}
  7. type QuiteHandle func(ctx QuitCtx) bool
  8. var _quitCtx = make(map[string]interface{})
  9. var _listeners = []QuiteHandle{}
  10. func InitQuitCtx(ctx QuitCtx) {
  11. _quitCtx = ctx
  12. }
  13. func PushQuitHandle(handle QuiteHandle) {
  14. _listeners = append(_listeners, handle)
  15. }
  16. func onQuite() {
  17. t := len(_listeners)
  18. for i, h := range _listeners {
  19. isBreak := h(_quitCtx)
  20. fmt.Println("[quit] ", i, "/", t, "breaking next =>", isBreak)
  21. if isBreak {
  22. break
  23. }
  24. }
  25. }
  26. var QuitChan = make(chan int)
  27. func InitQuitSocket(port int) error {
  28. if port <= 0 {
  29. p, e := GetFreePort()
  30. if e != nil {
  31. return e
  32. }
  33. port = p
  34. }
  35. ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
  36. if err != nil {
  37. fmt.Println("listen tcp err", err)
  38. return err
  39. }
  40. fmt.Println("quitsokect=>", port)
  41. go func() {
  42. // defer ln.Close()
  43. conn, err := ln.Accept()
  44. if err != nil {
  45. fmt.Println("Accept error=>", err)
  46. ln.Close()
  47. return
  48. }
  49. defer conn.Close() //接收
  50. onQuite()
  51. message := "pong"
  52. _, err = conn.Write([]byte(message))
  53. if err != nil {
  54. fmt.Println("Error sending message:", err)
  55. }
  56. QuitChan <- 1
  57. }()
  58. return nil
  59. }