package microservice import ( "context" "fmt" "net" "time" ) func NewSocketClient(host string, port uint16, bufSize int, ctx context.Context, receiveBuf int) *SocketClient { cctx, cancel := context.WithCancel(ctx) socket := &SocketClient{ host: host, port: port, bufSize: bufSize, receiveBuf: receiveBuf, ctx: cctx, cancel: cancel, } go socket.connect() return socket } type SocketClient struct { host string port uint16 bufSize int receiveBuf int ctx context.Context cancel context.CancelFunc socket *Socket } func (s *SocketClient) start() { //log.Println("Start(X)...") for { select { case <-s.ctx.Done(): //log.Println("XDONE--------------------------") return case <-s.socket.Context().Done(): //log.Println("DONE>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") s.connect() return } } } func (s *SocketClient) connect() { //log.Println("CONNECT(X)..............") for { select { case <-s.ctx.Done(): s.socket.Close() return default: //log.Println("CONNECT...") if conn, err := net.Dial("tcp", fmt.Sprintf("%v:%v", s.host, s.port)); err == nil { s.socket = NewSocket(conn, s.bufSize, s.ctx, s.receiveBuf) s.start() return } time.Sleep(time.Second) } } } func (s *SocketClient) Close() { //log.Println("CLIENT-CLOSE...") s.socket.Close() s.cancel() }