User1291
User1291

Reputation: 8182

Custom websocket handshake

I have a ServerEndpoint and a ClientEndpoint exchanging JSON messages via the respective encoders/decoders.

Now I want to add the ability for a client to choose a unique user name.

Let's say I have a fun isNameAvailable(name: String): Boolean (on the server, of course).

Haven't tried it, but I do think I could use a WebFilters to guard access to WebSocket endpoints. (e.g. let's say I connect to ws://localhost:8888/ws/foo and I add a web filter that intercepts all accesses to /ws/*) in which I'd query the user repeatedly for a user name and reject it until isNameAvailable returns true.

But in my understanding, that fails as soon as I add a non-browser client.

How can you write a "custom handshake"?

I.e. I want to repeatedly query the client for a String from within the ServerEndpoint's @OnOpen until one fits and only then continue with the rest of the setup, after which the client and the server can start exchanging the JSON messages. That is, something like this:

@ServerEndpoint("/foo")
class FooServerEndpoint{
    @OnOpen
    fun open(session:Session){
        var userName:String
        do{
            userName = requestUserName(session)
        }while(!acceptUserName(userName,session)
    }
}

Is there a way to do that?

UPDATE: Technology Used

JavaEE 8/Kotlin 1.3.21, deployed to a Glassfish 5 server and connected to by a Glassfish Tyrus 1.15-based client

Upvotes: 0

Views: 1056

Answers (1)

FlorianDe
FlorianDe

Reputation: 1242

Maybe have a look at creating a custom ServerEndpointConfig.Configurator and overload the modifyHandshake() method and apply this instance to your server endpoint as the configurator property of the @ServerEndpoint annotation? Similar answer here: https://stackoverflow.com/a/21766822/11133168

You could also find more details on this topic in the book "The Java EE 7 Tutorial" in Chapter 18.10

Upvotes: 1

Related Questions