Created
March 3, 2014 15:56
-
-
Save sukinull/9328010 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by sukinull on 2/14/14. | |
// Copyright (c) 2014 sukinull. All rights reserved. | |
// | |
// based on nopoll_pure.c - https://gist.github.com/sukinull/9327937#file-nopoll_pure-c | |
// add callback function for receive | |
// | |
#include <stdio.h> | |
#include <nopoll.h> | |
void cb_recv_handler(noPollCtx *ctx, noPollConn *conn, noPollMsg *msg, noPollPtr user_data) { | |
static int count = 0; | |
if (! nopoll_conn_is_ok (conn)) { | |
fprintf (stderr, "ERROR: received websocket connection close during wait reply..\n"); | |
return; | |
} | |
const noPollPtr m = nopoll_msg_get_payload(msg); | |
int n = nopoll_msg_get_payload_size(msg); | |
fprintf(stdout, "connection mesg: %s[%d]\n", m, n); | |
if(count > 3) { | |
nopoll_loop_stop(ctx); | |
return; | |
} | |
count++; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
noPollCtx * 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 | |
noPollConn * conn = nopoll_conn_new (ctx, "localhost", "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(stdout, "#"); | |
} | |
nopoll_ctx_set_on_msg(ctx, cb_recv_handler, NULL); | |
// send a message | |
if (nopoll_conn_send_text (conn, "Echo!", 5) != 5) { | |
// send a message | |
fprintf(stderr, "nopoll_conn_send_text is failed\n"); | |
nopoll_ctx_unref (ctx); | |
return 3; | |
} | |
#if 0 | |
/* 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(stdout, "connection mesg: %s[%d]\n", m, n); | |
if (! nopoll_conn_is_ok (conn)) { | |
printf ("ERROR: received websocket connection close during wait reply..\n"); | |
return nopoll_false; | |
} | |
#endif | |
nopoll_loop_wait(ctx, 0); | |
// 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