On 12/04/2023 19:31, Christopher Schultz wrote:
All,
I'm finally dipping my toes into Websocket-based communication with my
Tomcat-based applications. Is it possible to do everything with "real"
code and not any annotations?
I was looking for something like the Servlet Async model where you take
an existing request and put it into async mode:
final AsyncContext ac = request.startAsync(request, response);
ac.start(new Runnable() {
@Override
public void run() {
// Do some stuff
// Write the response
ac.complete();
}
});
All the tutorials I see use annotations to set up the Websocket
endpoint, etc.
Is it possible and/or recommended to use pure-code registration of such
endpoints and/or post-HTTP-request upgrade?
Configure an endpoint with code:
ServerContainer.addEndpoint(ServerEndpointConfig)
or
Upgrade an existing connection to WebSocket:
ServerContainer.upgradeHttpToWebSocket(...)
I'm wanting to do things like verify that the request belongs to an
authenticated user with certain privileges, etc. and only then allow
that user to connect using Websocket to trade data across the wire.
There are various ways to do that. Either the upgrade call above or a
custom ServerEndpointConfig.Configurator.modifyHandshake. The former has
more access to the Servlet objects so is probably what you want.
How can I relate a Websocket session to an authenticated user? Can I
communicate back and forth between the Websocket world and the
HTTP-based world like websocket.session <-> HttpSession?
Not easily. The lifecycles of the sessions diverge at the point of
upgrade. It is possible for the HttpSession to expire but the WebvSocket
session doesn't get notified.
You really need to set up everything at the point of the upgrade
including retaining a reference to the HttpSession if you wish.
There are various discussions of this - and how to keep them in sync -
on line.
It is less than ideal but there is no simple fix.
If I want to send a fire-and-forget message to the client from the
server, can I just:
session.getAsyncRemote().sendText("hello world");
and ignore the Future<?> object returned, or will I need to verify that
message was sent before attempting to send another one?
No. You need to make sure the previous message completed before you send
the next one.
Mark
---------------------------------------------------------------------
To unsubscribe, e-mail: users-unsubscr...@tomcat.apache.org
For additional commands, e-mail: users-h...@tomcat.apache.org