socket_client.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package microservice
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "time"
  7. )
  8. func NewSocketClient(host string, port uint16, bufSize int, ctx context.Context) *SocketClient {
  9. cctx, cancel := context.WithCancel(ctx)
  10. socket := &SocketClient{
  11. host: host,
  12. port: port,
  13. bufSize: bufSize,
  14. ctx: cctx,
  15. cancel: cancel,
  16. }
  17. go socket.connect()
  18. return socket
  19. }
  20. type SocketClient struct {
  21. host string
  22. port uint16
  23. bufSize int
  24. ctx context.Context
  25. cancel context.CancelFunc
  26. socket *Socket
  27. }
  28. func (s *SocketClient) start() {
  29. //log.Println("Start(X)...")
  30. for {
  31. select {
  32. case <-s.ctx.Done():
  33. //log.Println("XDONE--------------------------")
  34. return
  35. case <-s.socket.Context().Done():
  36. //log.Println("DONE>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
  37. s.connect()
  38. return
  39. }
  40. }
  41. }
  42. func (s *SocketClient) connect() {
  43. //log.Println("CONNECT(X)..............")
  44. for {
  45. select {
  46. case <-s.ctx.Done():
  47. s.socket.Close()
  48. return
  49. default:
  50. //log.Println("CONNECT...")
  51. if conn, err := net.Dial("tcp", fmt.Sprintf("%v:%v", s.host, s.port)); err == nil {
  52. s.socket = NewSocket(conn, s.bufSize, s.ctx)
  53. s.start()
  54. return
  55. }
  56. time.Sleep(time.Second)
  57. }
  58. }
  59. }
  60. func (s *SocketClient) Close() {
  61. //log.Println("CLIENT-CLOSE...")
  62. s.socket.Close()
  63. s.cancel()
  64. }