NetworkWebServerInterface Manual

About

The maxon::NetworkWebServerInterface allows to implement a simple web server. This server can be simply accessed with a web browser.

Interface

maxon::NetworkWebServerInterface allows to create, configure and start a simple web server:

// This example starts a simple web-server. The behaviour
// of the sever is defined with the callback function.
// create server instance
g_server = maxon::NetworkWebServerClass().Create() iferr_return;
const maxon::String name("ExampleServer"); // server name must pass maxon::IsAlphabetic()
const bool useSSL = false;
// start server
g_server.Init(useSSL, serverAddr, name) iferr_return;
g_server.StartServer(true) iferr_return;
DiagnosticOutput("WebServer started on port @", g_server.GetServerPort());
// define behaviour
g_server.ObservableHandleRequest().AddObserver(WebServerCallback) iferr_return;

Implementation

The behaviour of the web-server is defined by implementing the ObservableHandleRequest. The callback function reacts to an incoming HTTP request and can return a message or an error.

HTTP errors can be returned with maxon::HttpCodeError and defined with maxon::HTTPCODE.

// This callback function defines how the web-server acts.
// It checks the URL string and returns either text or an HTTP error.
static maxon::Result<void> WebServerCallback(const maxon::NetworkWebServerRef& server, const maxon::NetworkHttpHandlerRef& remoteConnection, const maxon::DataDictionary& request)
{
// get request and connection type
const maxon::HTTPREQUESTTYPE requestType = request.Get(maxon::HTTPREQUEST::TYPE, maxon::HTTPREQUESTTYPE());
const maxon::String connectionType = request.Get(maxon::HTTPREQUEST::CONNECTION) iferr_return;
const maxon::Bool keepAlive = connectionType.FindUpper("KEEP-ALIVE"_s, nullptr, 0);
// check request and connection type
const maxon::Bool isGetRequest = requestType == maxon::HTTPREQUESTTYPE::GET;
const maxon::Bool isPostRequest = requestType == maxon::HTTPREQUESTTYPE::POST;
const maxon::Bool isGetOrPostRequest = isGetRequest || isPostRequest;
if (isGetOrPostRequest && keepAlive)
{
// get path requested by the client
const maxon::String file = request.Get(maxon::HTTPREQUEST::FILE) iferr_return;
const maxon::String fileLower = file.ToLower();
// check for specific string
// the URL would look like "127.0.0.1:1234/marco"
if (fileLower == "marco"_s)
{
// prepare answer message
const maxon::String message { "polo" };
const maxon::Int length = message.GetLength();
// prepare header
const maxon::CString header = remoteConnection.CreateAnswerHeader("text/html"_s, length, maxon::HTTPCODE::OK);
// send header and answer
remoteConnection.SendString(header) iferr_return;
remoteConnection.SendString(message) iferr_return;
return maxon::OK;
}
// by default return 404
return maxon::HttpCodeError(MAXON_SOURCE_LOCATION, maxon::HTTPCODE::NOTFOUND);
}
}

Further Reading