Spring consume websocket

Manssouri 3 years ago

Hi, Sorry for disturbing you and thank you for your incredible work.

I'm a bit stuck.
from my "spring boot" gateway, I try to add positions to a device via the websocket.

I provide my code below. The connection is fine. The session is recovered but when I want to send a new position, nothing happens. The traccar server logs nothing, no error, and my breakpoints that I set on my browser in the "onmessage" method of the Root file are never reached.

My question is, is it possible to add positions/devices and send alerts via the websocket? If so, do you have any idea where my problem could come from?

Thanks a lot.

@ClientEndpoint
public class WebsocketClientEndpoint extends Endpoint {

    private Logger logger = Logger.getLogger(this.getClass().getName());
    @Value("${traccar.token}")
    private String token;
    Session session = null;


    public WebsocketClientEndpoint(String endpointURI) {
        //start connection
        javax.websocket.WebSocketContainer container = javax.websocket.ContainerProvider.getWebSocketContainer();
        try {
            ClientEndpointConfig.Configurator configurator = new ClientEndpointConfig.Configurator() {
                public void beforeRequest(Map headers) {
                    headers.put("Cookie", Arrays.asList(buildCookie(token)));
                    headers.put("Authorization", Arrays.asList(buildBearer(token)));
                }
            };
            ClientEndpointConfig clientConfig = ClientEndpointConfig.Builder.create()
                    .configurator(configurator)
                    .build();

            session = container.connectToServer(this,clientConfig, new URI(endpointURI));
            session.setMaxIdleTimeout(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onOpen(Session session, EndpointConfig config) {
        logger.info("Client onOpen..." + session.getId());


        this.session = session;
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("Response log: " + message);
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
        logger.info(String.format("Session %s close because of %s", session.getId(), closeReason));
    }

    public void sendMessage(Position position) {
        if (session != null) {
            String json2 = "{\"positions\":[ { \"temp\",\"content\":\"temp2\" } ]}";
            try {
                this.session.getBasicRemote().sendText(json2);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

(The variable "json2" is just fake data just to test if the server got the data)

Thank you

Anton Tananaev 3 years ago

You can't send positions via WebSocket. It's only for receiving data from the server.

Manssouri 3 years ago

Hi, okai, thank you for you response.