Thursday, March 20, 2014

Websockets with Spring Framework 3.x

Spring introduced support for WebSocket-style messaging in version 4.0, but how about spring 3.x?
- Can applications using spring framework 3.x have websocket endpoints integrated with spring's application context?

- Yes, they can.

I developed a small proof-of-concept application to demonstrate this.

This application sets up a websocket server endpoint with uri `/wstest` which will use a `@Autowired` spring bean to select a greeting word and reply to a websocket message.
The websocket connection is initiated and messages sent by an html page (`index.html`) running in a browser that supports websockets.

@Component
public class MyEndpoint extends Endpoint {
@Autowired
MyService myService;
@Override
public void onOpen(Session session, EndpointConfig config) {
session.addMessageHandler(new MyMessageHandler(session));
}
class MyMessageHandler implements MessageHandler.Whole<String> {
final Session session;
public MyMessageHandler(Session session) {
this.session = session;
}
@Override
public void onMessage(String message) {
try {
String greeting = myService.getGreeting();
session.getBasicRemote().sendText(greeting + ", got your message (" + message + "). Thanks ! (session: " + session.getId() + ")");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
view raw MyEndpoint.java hosted with ❤ by GitHub

The Servlet container's scan for WebSocket endpoints is avoided by not using the `@ServerEndpoint` annotation and instead implementing a ServerEndpointConfig and adding it to the server container upon servlet context initialization.
This way, the endpoint instance will be provided by SpringConfigurator, which means it can itself be a spring bean and/or it can have spring dependencies automatically injected with the `@Autowired` annotation.

Checkout the full source and ready to run example on my Github page.

You can run the webapp with jetty executing the maven command `mvn jetty:run`

  • start your browser and access the url `http://localhost:8080/websocket-test/index.html`
  • type a message, press the button "Send" and see the response message.

You can also deploy and run websocket-test in WildFly 8:
  • add `websocket-test.war` to `WILDFLY_HOME/standalone/deployments
  • start WildFly 8
  • start your browser and access the url `http://localhost:8080/websocket-test/index.html`
  • type a message, press the button "Send" and see the response message.

1 comment:

  1. Thanks for posting such an excellent informative content.

    ReplyDelete