In this post we show how to use websockets from the Modelit Webserver toolbox. This feature was recently added to the toolbox and makes it possible to have full-duplex communication between the client and the server. This means that the client as well as the server can send messages to the other, contrary to the conventional HTTP requests where the conversation is always initiated by the client. Websockets are more efficient than HTTP request because they maintain an active connection and do not require the HTTP request/response overhead for each message. This makes it suitable for realtime applications and applications with multiple clients.

Prerequisites for this example:

  1. Matlab (should work for all versions released after 2004)
  2. The Modelit Webserver toolbox.

For this example we need two components:

  1. The front-end (HTML plus Javascript)
  2. The back-end (Matlab with the Modelit Webserver toolbox)

Setting up the Matlab back-end is straightforward and consists of three steps:

  1. Create the Websocket server to listen to a specified port
  2. Define the callback to be triggered when a message from a client arrives
  3. Start the server

The code to achieve this is given in the next code block. Copy and paste this code and save it in a .m file named testWS.m

function server = testWS

server = nl.modelit.web.server.MatlabWebSocketServer(8000);
set(server,'serverInvokedCallback',@(o,e)cb(o, e));

server.start;

function cb(obj, event)
disp(event.getMessage)

This code creates a server that listens to messages arriving at port 8000 and executes a callback whenever a new message arrives. 
In this example the callback just displays the message on the Matlab console.

Setting up the front-end requires some (basic) HTML and Javascript and consists of the following steps:

  1. Make a HTML page
  2. Create the Websocket client
  3. Implement the Websocket methods (onopen, onclose and onmessage)

The code for this front-end is given below. Copy and paste this code and save it in a .html file named websocket.html

<!DOCTYPE HTML>

<html>
   <head>
      
      <script type = "text/javascript">
	     // Open a web socket
         let ws = new WebSocket("ws://localhost:8000");
			   
         function WebSocketTest() {
            
            if ("WebSocket" in window) {
               ws.onopen = function() {
                  // Web Socket is connected                  
               };
				
               ws.onmessage = function (evt) { 
				  document.getElementById("log").innerHTML = "Message is received: " + evt.data;
               };
				
               ws.onclose = function() { 
                  
                  // websocket is closed.
                  document.getElementById("log").innerHTML = "WebSocket is closed.";
               };
            } else {
              
               // The browser doesn't support WebSocket
               document.getElementById("log").innerHTML = "WebSocket NOT supported by your Browser!";
            }
         }
		 
		 function send(){
		   ws.send("Message sent by websocket.html");
		   document.getElementById("log").innerHTML += "Message sent to Matlab</br>";
		 }
      </script>
		
   </head>
   
   <body onload="WebSocketTest()">

	  <button onclick="send()">
        Send message to Matlab
      </button>
      <div id = "log">
         
      </div>
   </body>
</html>

This code creates a button which calls the send method to send a message to Matlab and a HTML div element that maintains a log of the incoming and outgoing messages. The websocket is created to listen to the same port as the Matlab Socketserver and the three methods of this class are implemented:

  1. onopen: specifies what should happen when the connection is ready to send and receive data
  2. onclose: specifies what should happen when the connection is terminated
  3. onmessage: specifies what to do when a message arrives. The data of the message can be found in the data field of the evt object

Start the Matlab back-end by running the function in the first code block:

>> server = testWS

Start the front-end with the Matlab command web and the path to the file with the Html code given in the previous code block.

>> web('file://<path>\websocket.html')

 Click on the button to send a message to Matlab

As mentioned before: Websockets make it possible to have a full-duplex communication between the server and (multiple) clients. By clicking on the 'Send Message' button a message is sent from the client to the server. To send messages from the server to all the connected clients use the following command:

server.broadcast('Message from Matlab')

N.B. the server in this command is the return argument from the call to the testWS function.