Skip to content

Instantly share code, notes, and snippets.

@jirihnidek
Last active December 19, 2015 18:08
Show Gist options
  • Save jirihnidek/5996105 to your computer and use it in GitHub Desktop.
Save jirihnidek/5996105 to your computer and use it in GitHub Desktop.
Example of WebSocket server implemented with WSLay and OpenSSL
/**
* \brief Wslay WebSocket infinite loop
*/
void *websocket_loop(void *arg)
{
struct Context *C = (struct vContext*)arg;
/*
* This structure is passed as *user_data* in callback functions.
*/
struct Session *session = CTX_current_session(C);
wslay_event_context_ptr wslay_ctx;
fd_set read_set, write_set;
struct timeval tv;
int ret;
struct wslay_event_callbacks callbacks = {
recv_callback,
send_callback,
NULL,
NULL,
NULL,
NULL,
on_msg_recv_callback
};
ret = http_handshake(C);
if(ret == -1) {
goto end;
}
wslay_event_context_server_init(&wslay_ctx, &callbacks, session);
/* "Never ending" loop */
while(1)
{
/* Initialize read set */
FD_ZERO(&read_set);
FD_SET(session->sockfd, &read_set);
/* Initialize write set */
FD_ZERO(&write_set);
FD_SET(session->sockfd, &write_set);
tv.tv_sec = VRS_TIMEOUT; /* User have to send something in 30 seconds */
tv.tv_usec = 0;
if( (ret = select(session->sockfd+1,
&read_set,
&write_set,
NULL, /* Exception not used */
&tv)) == -1)
{
printf("%s:%s():%d select(): %s\n",
__FILE__, __FUNCTION__, __LINE__, strerror(errno));
goto end;
/* Was event on the listen socket */
} else if(ret>0){
if(FD_ISSET(session->sockfd, &read_set)) {
if( wslay_event_recv(wslay_ctx) != 0 ) {
goto end;
}
}
if(FD_ISSET(session->sockfd, &write_set)) {
int error;
if( wslay_event_send(wslay_ctx) != 0 ) {
goto end;
}
}
}
}
end:
pthread_exit(NULL);
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment