Route SockJS connection at variable URL?

Viewed 359

Let's say I have a bunch of clients who all have their own numeric IDs. Each of them connect to my server through SockJS, with something like:

var sock = new SockJS("localhost:8080/sock/100");

In this case, 100 is that client's numeric ID, but it could be any number with any number of digits. How can I set up a SockJS router in my server-side code that allows for the client to set up a SockJS connection through a URL that varies based on what the user's ID is? Here's a simplified version of what I have on the server-side right now:

public void start() {
    HttpServer server = vertx.createHttpServer();
    SockJSHandler sockHandler = SockJSHandler.create(vertx);
    router.route("/sock/*").handler(sockHandler);
    server.requestHandler(router::accept).listen(8080);
}

This works fine if the client connects through localhost:8080/sock, but it doesn't seem to work if I add "/100" to the end of the URL. Instead of getting the default "Welcome to SockJS!" message, I just get "Not Found." I tried setting a path regex and I got an error saying that sub-routers can't use pattern URLs. So is there some way to allow for the client to connect through a variable URL, whether it's /sock/100, /sock/15, or /sock/1123123?

Ideally, I'd be able to capture the numeric ID that the client uses (like with routing REST API calls, when you could add "/:ID" to the routing path and then capture the value that the client uses), but I can't find anything that works for SockJS connections.

Since it seems that SockJS connections are considered to be the same as sub-routers, and sub-routers can't have pattern URLs, is there some work-around for this? Or is it not possible?

Edit

Just to add to what I said above, I've tried a couple different things which haven't seemed to work yet.

I tried setting up an initial, generic main router, which then re-directs to the SockJS handler. Here's the idea I had:

router.routeWithRegex("/sock/\\d+").handler(context -> {
    context.reroute("/final");
});

router.route("/final").handler(SockJSHandler.create(vertx));

With this, if I access localhost:8080/sock/100 directly through the browser, it takes me to the "Welcome to SockJS!" page, and the Chrome network tab shows that a websocket connection has been created when I test it through my client.

However, I still get an error because the websocket shows a 200 status code rather than 101, and I'm not 100% sure as to why that is happening, but I would guess that it has to do with the response that the initial handler produces. If I try to set the initial handler's status code to 101, I still get an error, because then the initial handler fails.

If there's some way to work around these status codes (it seems like the websocket is expecting 101 but the initial handler is expecting 200, and I think I can only pick one), then that could potentially solve this. Any ideas?

0 Answers
Related