Skip to content

Instantly share code, notes, and snippets.

@sukinull
Created March 3, 2014 15:58
Show Gist options
  • Save sukinull/9328054 to your computer and use it in GitHub Desktop.
Save sukinull/9328054 to your computer and use it in GitHub Desktop.
//
// Created by sukinull on 2/14/14.
// Copyright (c) 2014 sukinull. All rights reserved.
//
// With libuv
//
// based on nopoll_w_cb.c - https://gist.github.com/sukinull/9328010#file-nopoll_w_cb-c
// and integrated with libuv
//
#include <stdio.h>
#include <nopoll.h>
#include <uv.h>
static noPollCtx* ctx;
static noPollConn* conn;
void cb_nopoll_recv(uv_poll_t* handle, int status, int events)
{
/* wait for the reply */
noPollMsg *msg;
while ((msg = nopoll_conn_get_msg (conn)) == NULL) {
continue;
}
const noPollPtr m = nopoll_msg_get_payload(msg);
int n = nopoll_msg_get_payload_size(msg);
fprintf(stderr, "connection mesg: %s[%d]\n", m, n);
if (! nopoll_conn_is_ok (conn)) {
printf ("ERROR: received websocket connection close during wait reply..\n");
}
}
int main(int argc, char* argv[])
{
uv_loop_t* loop = uv_default_loop();
uv_poll_t handle;
ctx = nopoll_ctx_new ();
if (! ctx) {
// error some handling code here
fprintf(stderr, "nopoll_ctx_new is failed\n");
nopoll_ctx_unref (ctx);
return 1;
}
// call to create a connection
conn = nopoll_conn_new (ctx, "linode.sukinull.tw", "8000", NULL, NULL, NULL, NULL);
if (! nopoll_conn_is_ok (conn)) {
// some error handling here
fprintf(stderr, "nopoll_conn_new is failed\n");
nopoll_ctx_unref (ctx);
return 2;
}
while(nopoll_true != nopoll_conn_is_ready(conn)) {
fprintf(stderr, "#");
}
NOPOLL_SOCKET sfd = nopoll_conn_socket(conn);
nopoll_conn_set_sock_block(sfd, nopoll_false);
uv_poll_init_socket(loop, &handle, sfd);
uv_poll_start(&handle, UV_READABLE, cb_nopoll_recv);
// send a message
if (nopoll_conn_send_text (conn, "Echo!", 5) != 5) {
// send a message
fprintf(stderr, "nopoll_conn_send_text\n");
nopoll_ctx_unref (ctx);
return 3;
}
uv_run(loop, UV_RUN_DEFAULT);
// do some WebSocket operations (as client or listener)...
// ...and once you are done and after terminating all messages and
// connections created you have to release the context by doing the
// following:
nopoll_ctx_unref (ctx);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment