If you would like to upgrade to a newer long-term support version of Studio Pro, see Moving from Mendix Studio Pro 8 to 9.

WebSockets

Last modified: June 6, 2024

1 Introduction

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.

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import javax.websocket.CloseReason;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class TestEndpoint extends Endpoint {
  Set<Session> sessions = new HashSet<>();

  @Override
  public void onOpen(Session session, EndpointConfig config) {
    sessions.add(session);
    session.addMessageHandler(new MessageHandler.Whole<String>() {
      @Override
      public void onMessage(String message) {
        if ("test message".equals(message)) {
          try {
            session.getBasicRemote().sendText("test response");
            session.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    });

    try {
      session.getBasicRemote().sendText("socket opened");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onClose(Session session, CloseReason closeReason) {
    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 and closes the web socket