Category Archives: Open Source

Vector graphics rendering with cairo and openGL in Windows (VS project included)

Standard

OpenGL is not capable of rendering 2D vector graphics. Cairo can help in this situation. The basic working theory is outlined in cairo website. An example can be found in this post.  However, getting the code to work is not very straight forward, particularly with a Windows box. So I created this sample project with the code from the post mentioned above. Open the project file with VS 2013 (community edition is free), it should compile in both debug and release, it looks like this:

cairo_sample

checkout the source code for details.

Use Websockify in Windows

Standard

Recently, I ran into the problem of how to communicate between a TCP/IP socket server and a WebSocket client. Since TCP socket and WebSocket use different handshake, they cannot communicate directly. Some middle-ware is required to ‘bridge’ the two. After a little search, Websockify seems to be THE way to do it.  However, it took me a while to figure out how exactly to use it in Windows. So I decided to write about what I have learned with a demo.

  • Step 1.  To setup the demo, an Winsock echo server will be used. Copy the source code and compile it. This echo server listens to port 27015 and will send whatever message it received back to the client.
  • Step 2. Next, download Websockify zip file and unzip it on your machine. You can find posts about how to compile Websockify as Windows executable and even make it into a service. However, it does NOT work. I have wasted a lot of time went down this path. Instead, it’s easier to work with Node version of Websockify (websockify-master\other\js\websockify.js), and that’s what we are going to do.
  • Step 3. In order to run Node version Websockify, we need Node.js to be installed first.  Furthermore, Websockify requires a couple modules (optimist, policyfile, ws) not installed by default. We will have to install them manually. Once Node.js is installed, first lets check the installation is successful by opening a console window and type:
    node --version

    It will show the installed version of Node on your machine. check_node_installThe command to install modules is as follows:

    npm install -g modulename

    Replace ‘modulename‘ with optimist, policyfile and ws (i.e., run npm install three times) to install all three modules. You should be able to find them in the folder (assume your windows is installed on drive C):

    c:\\Users\%your account name%\AppData\Roaming\npm\npm_modules

Now, if you run Websockify.js, it most likely will complain about not finding files for optimist etc. That’s because the environment variable is not set yet.

  1. Go to: Control Panel\System and Security\System
  2. Click on “Advanced system settings”
  3. Click on “Environment Variables…”
  4. Create a new system variable named “NODE_PATH”, and set its value to  c:\\Users\%your account name%\AppData\Roaming\npm\npm_modules
  5. Add NODE_PATH to your PATH variable by attaching %NODE_PATH% to the end of “PATH”

That’s all the preparation work.  Now we are ready to run Websockify.js.

First, open a console window and get to the directory “websockify-master\other\js\”, then type:

node websockify.js localhost:27016 localhost:27015

Note that the parameters for websockify. the first is the address/port for the proxy websocket server, the second is the address/port for the ‘target’ tcp/ip echo server.

Next, run the echo server (the compile executable you get in Step 1).

To connect to the proxy server, I use Firefox console. Type the following command:

var sock=new WebSocket("ws://localhost:27016", ['binary','base64']);

ff_cmd
this will create a websocket client and connect to the proxy server.  The second parameter in the constructor ([‘binary’,’base64′]) are protocols required to be supported by the client.   If successful, the websockify console window will show messages like:

server

once the connection is established, we can communicate with the echo server through the proxy websocket server.  In Firefox console, type:

sock.send("hello");

The echo server will show number of types received (5 types for 5 characters in this case) and sent back.
tcp_server
Finally, we can close the echo server by typing:

sock.close();

This concludes our demo on how to use Websockify on Windows.

Test drive libwebsockets library – a simple server

Standard

This post shows how to use the libwebsockets library to build a server. This tutorial is largely derived from an old one with a little code modifications.
First of all, lets try out the end product.  Download the sample code, compile and run it. It’s a console application which will show some message telling you that the server is running and listing to port 9000:

web2_3

Next, open the ‘websocket_client.html’ included in the package, type something in the text box and hit ‘send’.  This sends the string to the server.  The server reverse the string and return it to the client.  You can also see from the console window what server did with the string.
web2_2

web2_1

now lets take a look on the code. first, you probably will notice ‘libwebsockets.h’, ‘websockets.lib’ and ‘websockets.dll’.  These are the files we get by compiling the libwebsockets library.  The header file is directly copied over from the source. Our code is in ‘server_test.cpp’ shown as follows:


#include <stdio.h>
#include <stdlib.h>
#include "libwebsockets.h"

#pragma comment(lib, "websockets.lib")

static int
callback_http(struct libwebsocket_context * that,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user,
void *in,
size_t len)
{
return 0;
}

static int
callback_dumb_increment(struct libwebsocket_context * that,
struct libwebsocket *wsi,
enum libwebsocket_callback_reasons reason,
void *user,
void *in,
size_t len)
{
switch (reason) {
case LWS_CALLBACK_ESTABLISHED: // just log message that someone is connecting
printf("connection established\n");
break;
case LWS_CALLBACK_RECEIVE: { // the funny part
// create a buffer to hold our response
// it has to have some pre and post padding. You don't need to care
// what comes there, libwebsockets will do everything for you. For more info see
// http://git.warmcat.com/cgi-bin/cgit/libwebsockets/tree/lib/libwebsockets.h#n597
unsigned char *buf = (unsigned char*) malloc(LWS_SEND_BUFFER_PRE_PADDING + len +
LWS_SEND_BUFFER_POST_PADDING);

// pointer to `void *in` holds the incomming request
// we're just going to put it in reverse order and put it in `buf` with
// correct offset. `len` holds length of the request.
for (size_t i=0; i < len; i++) {
buf[LWS_SEND_BUFFER_PRE_PADDING + (len - 1) - i ] = ((char *) in)[i];
}

// log what we recieved and what we're going to send as a response.
// that disco syntax `%.*s` is used to print just a part of our buffer
// http://stackoverflow.com/questions/5189071/print-part-of-char-array
printf("received data: %s, replying: %.*s\n", (char *) in, (int) len,
buf + LWS_SEND_BUFFER_PRE_PADDING);

// send response
// just notice that we have to tell where exactly our response starts. That's
// why there's `buf[LWS_SEND_BUFFER_PRE_PADDING]` and how long it is.
// we know that our response has the same length as request because
// it's the same message in reverse order.
libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], len, LWS_WRITE_TEXT);

// release memory back into the wild
free(buf);
break;
}
default:
break;
}

return 0;
}

static struct libwebsocket_protocols protocols[] = {
/* first protocol must always be HTTP handler */
{
"http-only",   // name
callback_http, // callback
0              // per_session_data_size
},
{
"dumb-increment-protocol", // protocol name - very important!
callback_dumb_increment,   // callback
0                          // we don't use any per session data
},
{
NULL, NULL, 0   /* End of list */
}
};

int main(void) {
struct libwebsocket_context *context;
// server url will be http://localhost:9000
// we're not using ssl
// no special options
struct lws_context_creation_info info;
memset(&info, 0, sizeof info);
info.port = 9000;
info.gid = -1;
info.uid = -1;
info.protocols = protocols;

// create libwebsocket context representing this server
context = libwebsocket_create_context(&info);

if (context == NULL) {
fprintf(stderr, "libwebsocket init failed\n");
return -1;
}

printf("starting server...\n");

// infinite loop, to end this server send SIGTERM. (CTRL+C)
while (1) {
libwebsocket_service(context, 50);
// libwebsocket_service will process all waiting events with their
// callback functions and then wait 50 ms.
// (this is a single threaded webserver and this will keep our server
// from generating load while there are not requests to process)
}

libwebsocket_context_destroy(context);

return 0;
}


Lets start with the main(), which shows the main workflow.

  1. Ln87 – 99 fill out a socket context structure (struct libwebsocket_context) which defines key attributes such as port, supported protocols etc.  And create a socket with it.
  2. Call libwebsocket_service() within a infinite loop to start the server, Ln 109-115
  3. call libwebsocket_context_destroy() to clean up before exit.  Ln 117

When you write your own server, you probably will not change much code in the main().  Instead, most of the work is in defining the supported protocols and its callbacks.

As seen in Ln 96, when defining supporting protocols for this server, we need to provide a ‘struct libwebsocket_protocols’ array (defined in Ln 69),  this array provides callbacks for each supported protocol.

The behavior of the server is mostly defined by these callbacks.  callback_dumb_increment() is where the server handles all different messages.  Especially, when there are data arrives from the client, it reverse the string.  The comments provide some details about the implementation.  You may also want to refer to ‘libwebsockets.h’.

On the client side, if you open ‘websocket_client.html’, you will see code that create and open a websocket, as well as the handler for receiving result from server.

That concludes a simple server written with libwebsockets library.

wxWidgets test drive in Visual Studio

Standard

wxWidgets as a cross-platform library for GUI programming is pretty neat.  I kind of feel that it’s easier to use it in Linux than in Windows. However, without knowing how to use it in both OS, the word cross-platform is really meaningless.

So I started out with using the binary directly instead of compile it in windows. The instructions are pretty straight forward as listed here:

wxWidgets blog

Just one thing, remember to add UNICODE macro in your Visual Studio project. Otherwise, the compiler will complain as it look for ASCII version dlls and libs which is not included in the downloaded binary file.