Cebsocket is a lightweight websocket library for C.
Usage is easy and simple. You can look to examples/
directory. You can build examples with make
command.
Here is an example for creating simple WebSocket server.
void on_data(cebsocket_clients_t* client, char* data) {
printf("WebSocket Message: %s\n", data);
char answer[500];
sprintf(answer, "Answer to client: %s", data);
cebsocket_send(client, answer);
sprintf(answer, "Answer to broadcast: %s", data);
cebsocket_send_broadcast(client, answer);
}
void on_connected(cebsocket_clients_t* client) {
printf("Client connected #%d\n", client->id);
}
void on_disconnected(cebsocket_clients_t* client) {
printf("Client disconnected #%d\n", client->id);
}
int main() {
printf("Starting WebSocket server..\n");
cebsocket_t* ws = cebsocket_init(8080);
ws->on_data = on_data;
ws->on_connected = on_connected;
ws->on_disconnected = on_disconnected;
cebsocket_listen(ws);
return 0;
}
Cebsocket is designed to only handle WebSocket requests as a HTTP server. You can use it with Apache's mod_proxy_ws_tunnel.
Also you can use Apache's mod_proxy_ws_tunnel for SSL.
Building is simple just do make
.
make clean; make
You will see websocket.o
. You can use it like:
gcc -o hello hello.c websocket.o
./hello
Event handler functions get called from client thread so you must be sure for they are thread-safe.
Called when a client
connected.
Called when a client
disconnected.
Called when a message is arrived from client
.
Creates WebSocket server instance.
Starts listening new connections.
Sends message
to client
.
Sends message
to boradcast of client
.
Sends message
to all clients.
Since ws->clients
is a linked-list, you can iterate it like the following example.
cebsocket_clients_t* _client = ws->clients;
while (_client) {
cebsocket_send(_client, message);
_client = _client->next;
}
The WebSocket server instance.
typedef struct cebsocket {
int port;
char* host_address;
char* bind_address;
cebsocket_clients_t* clients;
cebsocket_clients_t* current_client;
void (*on_data)(cebsocket_clients_t*, char*);
void (*on_connected)(cebsocket_clients_t*);
void (*on_disconnected)(cebsocket_clients_t*);
} cebsocket_t;
The WebSocket client instance. It is also a linked-list.
typedef struct cebsocket_clients {
cebsocket_t* ws;
int id;
int socket;
int server_socket;
int address;
char* ws_key;
void* data;
cebsocket_clients_t* prev;
cebsocket_clients_t* next;
} cebsoket_clients_t;
MIT