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.


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.