1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| #include <libwebsockets.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <signal.h>
static int interrupted = 0; static struct lws* client_wsi = NULL;
static void signal_handler(int sig) { interrupted = 1; }
static int callback_ws(struct lws* wsi, enum lws_callback_reasons reason, void* user, void* in, size_t len) { switch (reason) { case LWS_CALLBACK_CLIENT_ESTABLISHED: printf("Connected to server\n"); fflush(stdout); lws_callback_on_writable(wsi); break;
case LWS_CALLBACK_CLIENT_RECEIVE: printf("Received from server: %s\n", (char*)in); fflush(stdout); lws_callback_on_writable(wsi); break;
case LWS_CALLBACK_CLIENT_WRITEABLE: { char msg[128]; printf("Enter message: "); fflush(stdout); fgets(msg, sizeof(msg), stdin);
size_t msg_len = strlen(msg); if (msg[msg_len - 1] == '\n') { msg[msg_len - 1] = '\0'; msg_len--; }
unsigned char buf[LWS_PRE + 128]; memcpy(&buf[LWS_PRE], msg, msg_len); lws_write(wsi, &buf[LWS_PRE], msg_len, LWS_WRITE_TEXT);
printf("Sent: %s\n", msg); fflush(stdout); break; }
case LWS_CALLBACK_CLOSED: printf("Connection closed\n"); fflush(stdout); client_wsi = NULL; break;
default: break; } return 0; }
static struct lws_protocols protocols[] = { { "ws-protocol", callback_ws, 0, 1024 }, { NULL, NULL, 0, 0 } };
int main() { struct lws_context_creation_info info = { 0 }; struct lws_client_connect_info ccinfo = { 0 }; struct lws_context* context;
signal(SIGINT, signal_handler);
info.port = CONTEXT_PORT_NO_LISTEN; info.protocols = protocols; context = lws_create_context(&info); if (!context) { fprintf(stderr, "LWS init failed\n"); return -1; }
ccinfo.context = context; ccinfo.address = "10.0.1.20"; ccinfo.port = 9001; ccinfo.path = "/"; ccinfo.host = ccinfo.address; ccinfo.origin = ccinfo.address; ccinfo.protocol = "ws-protocol"; ccinfo.ssl_connection = 0; ccinfo.pwsi = &client_wsi;
if (!lws_client_connect_via_info(&ccinfo)) { fprintf(stderr, "Failed to connect\n"); lws_context_destroy(context); return -1; }
while (!interrupted) { lws_service(context, 100); }
lws_context_destroy(context); return 0; }
|