The Mendix Runtime supports registering custom web socket endpoints using the javax.websocket API.
All you need to do is to use the method Core.addWebSocketEndpoint(String path, Endpoint endpoint) to register an instance of javax.websocket.Endpoint to respond to web socket requests on the given path. The Session ID of the client can be obtained from the EndpointConfig given in the onOpen method of the Endpoint.
As with Core#addRequestHandler, adding a web socket end point only happens on the current cluster node. It is therefore a good practice to call it in an After Startup microflow.
Below is an example of how to register a websocket in your Mendix app.
2 Example
A simple implementation of an endpoint is shown below.
importjavax.websocket.CloseReason;importjavax.websocket.Endpoint;importjavax.websocket.EndpointConfig;importjavax.websocket.MessageHandler;importjavax.websocket.Session;importjava.io.IOException;importjava.util.HashSet;importjava.util.Set;importjava.util.UUID;importcom.mendix.core.Core;publicclassTestEndpointextendsEndpoint{Set<Session>sessions=newHashSet<>();@OverridepublicvoidonOpen(Sessionsession,EndpointConfigconfig){StringsessionId=(String)config.getUserProperties().get("mxSessionId");ISessionmxSession=Core.getSessionById(UUID.fromString(sessionId));Stringusername=mxSession.getUserName();sessions.add(session);session.addMessageHandler(newMessageHandler.Whole<String>(){@OverridepublicvoidonMessage(Stringmessage){if("test message".equals(message)){try{session.getBasicRemote().sendText("test response:"+username);session.close();}catch(IOExceptione){e.printStackTrace();}}}});try{session.getBasicRemote().sendText("socket opened");}catch(IOExceptione){e.printStackTrace();}}@OverridepublicvoidonClose(Sessionsession,CloseReasoncloseReason){System.out.println("Received onClose call with reason: "+closeReason);sessions.remove(session);}}
If this endpoint is registered by calling Core.addWebSocketEndpoint("/my-endpoint", new websockets.TestEndpoint()); then the following functionality is available at ws://.../my-endpoint:
When a connection is established, the server will send the message socket opened
If the client sends the message test message, the server responds with test response: USERNAME and closes the web socket