There is not much to explain, Websocket is being used widely for realtime notifications over the web and Duda I/O supports websocket through a package. I have written a simple chat example at server side to demostrate how it can be used, the front-end part is a tweaked client where i just performed minor modifications:
The interest part is the service code side:
#include "webservice.h"
#include "packages/websocket/websocket.h"
DUDA_REGISTER("Duda I/O Examples", "WebSocket Chat");
void cb_on_message(duda_request_t *dr, ws_request_t *wr)
{
websocket->broadcast(wr, wr->payload, wr->payload_len, WS_OPCODE_TEXT);
}
void cb_handshake(duda_request_t *dr)
{
websocket->handshake(dr);
}
int duda_main()
{
/* Load the websocket package */
duda_load_package(websocket, "websocket");
/*
* Define a callback, on every websocket message received,
* trigger cb_on_message.
*/
websocket->set_callback(WS_ON_MESSAGE, cb_on_message);
/* Associate a static URL with a callback */
map->static_add("/handshake/", "cb_handshake");
/* Initialize the broadcaster interface */
websocket->broadcaster();
return 0;
}
In duda_main() we initialize the web service, loading the websocket package and setting a callback function to invoke when a websocket message arrives. Then we map the URL path who wWebsocket handshake and finally we instruct the websocket package to launch the Broadcaster service, this last one is necessary if you want to send broadcast messages.
Getting started
If you want a simple steps to try this example do:
- git clone git://git.monkey-project.com/dudac
- git clone git://git.monkey-project.com/duda-examples
- cd dudac/ && ./dudac -g
- ./dudac -w /path/to/duda-examples/050_websocket_chat/
Now you can point your browser at http://localhost:2001/wschat/
Documentation
For more details about the Websocket package and its available methods, please refer to the Websocket API documentation