Web sockets have a habit of being messy, uncontrolled, and difficult to implement.
This library sorts that out by implementing a channel approach, and removing all the muck that may come using them.
All Guiced EE Servlet addons come with Undertow 2.x
<dependency> <groupId>com.guicedee.servlets</groupId> <artifactId>guiced-websockets</artifactId> </dependency>By default web sockets are available at the
"/"
location (so.. everywhere), and the group Everyone
contains everyone currently connected
Sending a message to a particular broadcast group is as simple as
GuicedWebSocket.broadcastMessage("Everyone","Hello")
GuicedWebSocket.addToGroup("Everyone",wsSession)
GuicedWebSocket.removeFromGroup("Everyone",wsSession)
Each message that is sent on the web socket should be structured in the following manner
{ action:"", broadcastGroup:"", data:{} }Messages going out can be anything. This structure is defined in the
WebSocketMessageReceiver
class.
You can then build your Web Socket listener for specific actions/message types. You can assign as many receiver to a type as necessary.
This allows modules to define which messages that they will listen for on receipt and loosely couples any child modules from base operation
public class PageConnectListener implements IWebSocketMessageReceiver { @Override public Set<String> messageNames() { Set<String> actionsListeningTo = new HashSet(); actionsListeningTo.add("DefaultPageConnect"); return actionsListeningTo; } @Override public void receiveMessage(WebSocketMessageReceiver message) throws SecurityException { System.out.println("Message broadcast by group/user : " + message.getBroadcastGroup()); } }
provides IWebSocketMessageReceiver with PageConnectListener;A web site may connect to the websocket perhaps like this in JavaScript
new WebSocket("ws://localhost/")
You may also want to intercept any messages without using this provided for datastructure, and hit the direct interceptions.
The following Service Providers are made available for you to operate with
IWebSocketService - onOpen(), onClose(), onMessage(), onError() IWebSocketSessionProvider - Retrieve sessions associated with web socket connection IWebSocketPreConfiguration - Perform any sort of configuration before web socket start, separete to IGuicePreStartup IWebSocketAuthDataProvider - Convenience method for authorization providers separately stored