The Modelit Webserver Toolbox for Matlab makes it possible to deploy algorithms written in Matlab code as a webservice. Central to the toolbox is a servlet that runs in Apache Tomcat and which redirects incoming web-requests to Matlab callback functions. Using Apache Tomcat has advantage that it is a proven technology with a lot of features. However it introduces an extra component which causes extra complexity and makes the use of Matlab algorithms in Docker containers overly complicated. As a solution Modelit has extended the Webserver toolbox with an embedded server, based on the Java Sun HTTP server. This server runs inside Matlab and makes it possible for Matlab to directly send and receive HTTP messages.
In this example we make a simple application in Matlab that can receive HTTP requests by using the Embedded Matlab server from the Modelit webserver toolbox. This application can be used as a standalone server or as part of a Docker container.
Let's start with a simple function that we want to run as a service.
function output = algorithm(input) |
This algorithm can be converted to a Matlab webservice by executing the following nine steps:
- Create a modelit.web.server.Server that can receive HTTP requests on a specific port.
- Define a callback that is executed when an HTTP request arrives.
- Start the server and make sure that the services stays active by running an eternal loop.
- Get the data from the (modelit.web.server.HttpExchange) event.
- Convert the data (e.g. JSON of XML) to a format that can be used by Matlab.
- Create the response by executing the algorithm.
- Convert the response to the required output format (e.g. JSON of XML).
- Set de HTTP headers (e.g. Content-Type).
- Send the response and HTTP statuscode to the client.
By following these nine step the following code is created:
% Create a server that listen to HTTP requests on port 8081 % Start the webservice. % Set the MIME type |