libwebsock – C WebSockets Library
Update: I have noticed that many people looking for a C WebSocket library are ending up hitting this page. This information is slightly out-of-date. You can find general information about my WebSocket library here and the GitHub with some documentation in the wiki here. Thanks for your interest. Let me know if you end up using it, can’t get it to work, or would like some additional features.
I got all fired up about the new (not so new, anymore) things with HTML5 after looking at Google’s Chrome Web Lab. They’ve got some pretty nifty things going on there. Anyway, what really grabs my interest as of late are WebSockets and WebGL and the endless possibilities of what they bring to the browser. I wanted to get in on the action, so I began thinking about a PHP implementation of a WebSocket server. Because I wanted to jump right in to playing with WebSockets, I began writing a little C library to handle the protocol specifics and abstract them away in a manner I found satisfactory. I’m still very early on in this little project, but you can find the source at http://github.com/payden/libwebsock. I haven’t really thought about somehow tying this into a PHP extension, but I’ll worry about that later. For now, I’m going to hammer out a decent stable C library for handling the WebSocket frames. If nothing else, I’ll be sharpening my C skills a bit. I’m still nowhere near where I want to be as far as C programming. Below is what libwebsock provides as of *right now*.
#include <stdio.h>
#include <stdlib.h>
#include <websock/websock.h>
/*
Define message callback with same prototype as below.
Accepts libwebsock_client_state structure and libwebsock_message structure.
libwebsock_client_state has several fields. The most important is sockfd, the socket descriptor for the client
libwebsock_message has unsigned int opcode, unsigned long long payload_len, and char *payload
*/
int my_message_callback(libwebsock_client_state *state, libwebsock_message *msg) {
printf("Received message from %d\n",state->sockfd);
printf("Opcode: %d\n",msg->opcode);
printf("Payload length: %llu\n", msg->payload_len);
printf("\n\n");
libwebsock_send_text(state->sockfd, msg->payload);
return 0;
}
int main(int argc, char **argv) {
libwebsock_context *ctx;
ctx = (libwebsock_context *)libwebsock_init("3333");
libwebsock_set_receive_cb(ctx, &my_message_callback);
libwebsock_wait(ctx);
return 0;
}
The above code when linked against libwebsock provides a WebSocket echo server. Echoing back whatever was sent by the client and outputting some debug information to the console of the program.
For example, in browsers that support it, you could do the following in JavaScript after starting that server up:
> ws = new WebSocket("localhost:3333");
> ws.onmessage = function(evt) { console.log(evt.data); };
> ws.send("Testing...");
"Testing..."
>
Cheers.

No comments yet.