comment
[libex.git] / test / test_ws_srv.c
blob6d98659bf6f386c6da2065ef0f7b60d5ad8dd19e
1 #include "../include/libex/wsnet.h"
2 #include "linenoise.h"
4 net_srv_t *srv;
6 static void sigexit (int sig) {
7 if (SIGTERM == sig || SIGINT == sig)
8 ws_srv_done(srv);
11 static void setsig () {
12 struct sigaction sa;
13 sa.sa_handler = sigexit;
14 sa.sa_flags = 0;
15 sigemptyset(&sa.sa_mask);
16 sigaction(SIGTERM, &sa, NULL);
17 sigaction(SIGINT, &sa, NULL);
20 static void *on_start (void *dummy) {
21 ws_srv_start(srv);
22 printf("end thread\n");
23 return NULL;
26 static void term (uint64_t fd) {
27 char *s;
28 do {
29 s = linenoise("> ", NULL);
30 if ('\0' != *s && 0 != strcmp("quit", s)) {
31 int len = strlen(s);
32 ws_ev_send(srv, fd, 0, s, len, WS_FIN, WS_TEXT);
34 } while (0 != strcmp("quit", s));
35 ws_ev_disconnect(srv, fd);
36 ws_srv_done(srv);
39 static int on_handle (ev_buf_t *ev) {
40 char *s = strndup((const char*)ev->data.ws.ptr, ev->data.ws.len);
41 printf("%s\n", s);
42 free(s);
43 return NET_OK;
46 int main (int argc, const char *argv[]) {
47 int is_client = 1;
48 pthread_t th;
49 if (2 != argc) return 1;
50 if (0 == strcmp("server", argv[1]))
51 is_client = 0;
52 else
53 if (0 != strcmp("client", argv[1]))
54 return 1;
55 printf("[%d]\n", getpid());
56 if (is_client) {
57 ev_fd_t fd;
58 srv = ws_srv_init(NULL);
59 srv->on_handle = on_handle;
60 srv->tm_connect = 8;
61 printf("Ok\n");
62 pthread_create(&th, NULL, on_start, NULL);
63 sleep(1);
64 if (0 == (fd = net_ev_connect(srv, CONST_STR_LEN("ws://127.0.0.1:7878/")))) {
65 printf("(%d) %s\n", errno, strerror(errno));
66 ws_srv_done(srv);
67 } else
68 term(fd);
69 } else {
70 setsig();
71 srv = ws_srv_init("7878");
72 srv->on_handle = on_handle;
73 printf("Ok\n");
74 ws_srv_start(srv);
76 return 0;