10

Is there any way to do this?

Client side:

function connectWebSocket() {
    var socket = new SockJS('/socket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log("connected");
    });
}

Server side is not important. After the code above has been executed I need to know my session id.

sinedsem
  • 5,413
  • 7
  • 29
  • 46

3 Answers3

12

You can get it from url without making any changes into SockJS library.

var socket = new SockJS('/mqClient');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
        console.log(socket._transport.url); 
        //it contains ws://localhost:8080/mqClient/039/byxby3jv/websocket
        //sessionId is byxby3jv
    });
mariusz2108
  • 851
  • 2
  • 11
  • 36
  • 1
    I have provided a Regular Expression for parsing the session id out, in [my answer to _Spring Websockets @SendToUser without login?_](http://stackoverflow.com/a/43430736/1847378) – AndrewL Apr 15 '17 at 20:09
  • 2
    Do you know what the /039/ is? – zudduz Jun 21 '17 at 21:25
9

The SockJS constructor has an option parameter and there you can pass a custom session id generator as a function:

let sessionId = utils.random_string(8);
let socket = new SockJS('/socket', [], {
    sessionId: () => {
       return sessionId
    }
 });
tandris
  • 91
  • 1
  • 1
1

To get session id we need to make some changes into SockJS library.
The string

var connid = utils.random_string(8);

is used to get our id. So, we need only complete it like this:

var connid = utils.random_string(8);
that.sessionId = connid;

and then we can read this field from the client code:

function connectWebSocket() {
    var socket = new SockJS('/socket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log("connected, session id: " + socket.sessionId);
    });
}

And if we need to know session id before calling connect method we can modify SockJS' constructor and connect method to use client-passed value.

sinedsem
  • 5,413
  • 7
  • 29
  • 46