socket_client.go 1.4 KB

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