Wslay's event-based API relies on three primary callbacks defined in struct wslay_event_callbacks to bridge the library with your socket I/O:
recv_callback: Invoked by wslay_event_recv when the library needs to read data from the client.
- If the underlying
recv returns EAGAIN or EWOULDBLOCK, call wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK) to tell the library to stop reading for now. - For other errors or unexpected EOF, call
wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE).
send_callback: Invoked by wslay_event_send when the library needs to transmit data to the client.
- Handle
EAGAIN or EWOULDBLOCK by calling wslay_event_set_error(ctx, WSLAY_ERR_WOULDBLOCK). - Handle other errors by calling
wslay_event_set_error(ctx, WSLAY_ERR_CALLBACK_FAILURE).
on_msg_recv_callback: Invoked by wslay_event_recv when a complete WebSocket message has been assembled.
- Use
wslay_is_ctrl_frame(arg->opcode) to distinguish between control frames and data frames. - Use
wslay_event_queue_msg(ctx, &msgarg) to queue a message (e.g., for echoing).
struct wslay_event_callbacks callbacks = {
recv_callback,
send_callback,
NULL,
NULL,
NULL,
NULL,
on_msg_recv_callback
};
/* Example on_msg_recv_callback for an echo server */
void on_msg_recv_callback(wslay_event_context_ptr ctx,
const struct wslay_event_on_msg_recv_arg *arg,
void *user_data) {
if(!wslay_is_ctrl_frame(arg->opcode)) {
struct wslay_event_msg msgarg = {
arg->opcode, arg->msg, arg->msg_length
};
wslay_event_queue_msg(ctx, &msgarg);
}
}