Spring Websockets @SendToUser without login?

后端 未结 4 1772
梦毁少年i
梦毁少年i 2020-12-09 04:52

I have a simple spring application with websocket functionality and everything works so far. Now I want to send a message from my server to a specific client using the @Send

4条回答
  •  独厮守ぢ
    2020-12-09 05:16

    Building on Biju's answer and using the Stomp generated session id (thanks, mariusz2108 in his answer to a similar question), here's what worked for me (based on the canonical example from Spring)

    SpringFramework client:

    private SimpMessagingTemplate template;
    
    @Autowired
    public GreetingController(SimpMessagingTemplate template) {
        this.template = template;
    }
    
    @MessageMapping("/hello")
    public void greeting(HelloMessage message, @Header("simpSessionId") String sessionId) throws Exception {
        template.convertAndSend("/queue/greeting-"+sessionId, new Greeting("Hello, " + message.getName()));
    }
    

    JavaScript client:

    function connect() {
        var socket = new SockJS('/gs-guide-websocket');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            var sessionId = /\/([^\/]+)\/websocket/.exec(socket._transport.url)[1];
            console.log("connected, session id: " + sessionId);
            stompClient.subscribe('/queue/greeting-'+sessionId, function (greeting) {
                showGreeting(JSON.parse(greeting.body).content);
            });
        });
    }
    

    Instead of the Stomp session id you could use your web container's Session ID (e.g. JSESSIONID) but now that cookie is not by default accessible from JavaScript (for Tomcat) this is a more difficult prospect.

提交回复
热议问题