From c5a9fc2f7732306a8df418b0e66d97a61c912b35 Mon Sep 17 00:00:00 2001 From: 1998-felix Date: Thu, 25 Apr 2024 15:20:30 +0300 Subject: [PATCH] fix: increase keep alive for connection Signed-off-by: 1998-felix --- internal/server/coap/coap.go | 56 +++++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 14 deletions(-) diff --git a/internal/server/coap/coap.go b/internal/server/coap/coap.go index 6bdc496e498..5b9ea11a98e 100644 --- a/internal/server/coap/coap.go +++ b/internal/server/coap/coap.go @@ -10,13 +10,16 @@ import ( "time" "github.com/absmach/magistrala/internal/server" - gocoap "github.com/plgd-dev/go-coap/v3" "github.com/plgd-dev/go-coap/v3/mux" + "github.com/plgd-dev/go-coap/v3/net" + "github.com/plgd-dev/go-coap/v3/options" + "github.com/plgd-dev/go-coap/v3/udp" + udpClient "github.com/plgd-dev/go-coap/v3/udp/client" ) -const ( - stopWaitTime = 5 * time.Second -) +// const ( +// stopWaitTime = 5 * time.Second +// ) type Server struct { server.BaseServer @@ -44,26 +47,51 @@ func (s *Server) Start() error { errCh := make(chan error) s.Logger.Info(fmt.Sprintf("%s service started using http, exposed port %s", s.Name, s.Address)) s.Logger.Info(fmt.Sprintf("%s service %s server listening at %s without TLS", s.Name, s.Protocol, s.Address)) + l, err := net.NewListenUDP("udp", s.Address) + if err != nil { + return err + } + defer l.Close() + + s.Logger.Info(fmt.Sprintf("CoAP proxy server started at %s without DTLS", s.Address)) + + dummyInactiveFunc := func(cc *udpClient.Conn) { + // This function intentionally left blank. + } + cs := udp.NewServer( + options.WithMux(mux.HandlerFunc(s.handler)), + options.WithKeepAlive(10, 10*time.Minute, dummyInactiveFunc), + ) + go func() { - errCh <- gocoap.ListenAndServe("udp", s.Address, s.handler) + errCh <- cs.Serve(l) }() select { case <-s.Ctx.Done(): - return s.Stop() + s.Logger.Info(fmt.Sprintf("CoAP proxy server at %s without DTLS exiting ...", s.Address)) + l.Close() case err := <-errCh: + s.Logger.Error(fmt.Sprintf("CoAP proxy server at %s without DTLS exiting with errors: %s", s.Address, err.Error())) return err } + return nil + // select { + // case <-s.Ctx.Done(): + // return s.Stop() + // case err := <-errCh: + // return err + // } } func (s *Server) Stop() error { - defer s.Cancel() - c := make(chan bool) - defer close(c) - select { - case <-c: - case <-time.After(stopWaitTime): - } - s.Logger.Info(fmt.Sprintf("%s service shutdown of http at %s", s.Name, s.Address)) + // defer s.Cancel() + // c := make(chan bool) + // defer close(c) + // select { + // case <-c: + // case <-time.After(stopWaitTime): + // } + // s.Logger.Info(fmt.Sprintf("%s service shutdown of http at %s", s.Name, s.Address)) return nil }