Reputation: 2133
I have a jetty 9.3.6 server that runs a websocket webapp. I would like to get the client IP address for bookeeping purposes, and I can see it is there in the javax.websocket.Session
object, but I don't know how to get it as the API doesn't allow for it. Some folks seem to cast it to a TyrusSession
object (from org.glassfish.tyrus.core.TyrusSession
), but when I tried that, it compiled fine, but raised a ClassCastException
in the websocket server at runtime. I have included the following in my build.gradle
:
compile 'org.glassfish.tyrus:tyrus-core:1.12'
What's the correct way to get the client IP address in a javax.websocket.Session
?
Upvotes: 0
Views: 2700
Reputation: 2133
Consistent with the SO rules, I answer my own question here.
I got my clue when I tried to cast it to TyrusSession
and Jetty complained (raised ClassCastException
) in the error logs saying it was a JsrSession
which cannot be cast into a TyrusSession
. However, I had just printed the Session
object in my logs, and something like this showed up:
session: WebSocketSession[....]
I then tried to cast it to org.eclipse.jetty.websocket.common.WebSocketSession
which then complained about the object actually being a JsrSession
which then led to my discovering the following solution:
@ServerEndpoint (value="/mySillyApp", configurator= ..., decoders={...})
public class MySillyWebSocketServer
{
@OnOpen
public void open (Session session, EndpointConfig config)
{
JsrSession jsrSession = (JsrSession) session; // import org.eclipse.jetty.websocket.jsr356.JsrSession;
WebSocketSession webSocketSession = jsrSession.getWebSocketSession (); // import org.eclipse.jetty.websocket.common.WebSocketSession;
String clientIPAddressString = webSocketSession.getRemoteAddress ().getHostString ();
....
}
...
}
Obviously, you will have to include the appropriate jars in your classpath. For gradle, you do this in the dependencies {...}
section:
compile 'org.eclipse.jetty.websocket:javax-websocket-client-impl:9.3.6.v20151106'
compile 'org.eclipse.jetty.websocket:websocket-common:9.1.0.v20131115'
Hope my methodology and details helps someone.
Upvotes: 2