Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // libwebsocketsserver.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #ifdef _WIN32
- #include <io.h>
- #else
- #include <unistd.h>
- #endif
- #include <signal.h>
- #include <libwebsockets.h>
- #define KGRN "\033[0;32;32m"
- #define KCYN "\033[0;36m"
- #define KRED "\033[0;32;31m"
- #define KYEL "\033[1;33m"
- #define KMAG "\033[0;35m"
- #define KBLU "\033[0;32;34m"
- #define KCYN_L "\033[1;36m"
- #define RESET "\033[0m"
- static int destroy_flag = 0;
- static void INT_HANDLER(int signo) {
- destroy_flag = 1;
- }
- static int callback_http(
- struct lws *wsi,
- enum lws_callback_reasons reason, void *user,
- void *in, size_t len)
- {
- switch (reason) {
- // http://git.warmcat.com/cgi-bin/cgit/libwebsockets/tree/lib/libwebsockets.h#n260
- case LWS_CALLBACK_CLIENT_WRITEABLE:
- printf("connection established\n");
- // http://git.warmcat.com/cgi-bin/cgit/libwebsockets/tree/lib/libwebsockets.h#n281
- case LWS_CALLBACK_HTTP: {
- char *requested_uri = (char *)in;
- printf("requested URI: %s\n", requested_uri);
- /*if (strcmp(requested_uri, "/") == 0) {
- lws_return_http_status(wsi, 200, "Hello, World!\0");
- // http://git.warmcat.com/cgi-bin/cgit/libwebsockets/tree/lib/libwebsockets.h#n597
- //lws_write(wsi, universal_response,
- // strlen((const char*)universal_response), LWS_WRITE_HTTP);
- lws_http_transaction_completed(wsi);
- break;
- }
- else {*/
- if (strcmp(requested_uri, "index.html\0") != 0 && strcmp(requested_uri, "/\0") != 0) {
- printf("returning 404\n");
- lws_return_http_status(wsi, 404, "Only index.html is returned");
- lws_http_transaction_completed(wsi);
- break;
- }
- char *resource_path = "./index_cpp.html";
- printf("Returned resource path: %s\n", resource_path);
- char *mime = "text/html";
- // by default non existing resources return code 400
- // for more information how this function handles headers
- // see it's source code
- // http://git.warmcat.com/cgi-bin/cgit/libwebsockets/tree/lib/parsers.c#n1896
- lws_serve_http_file(wsi, resource_path, mime,"",0);
- //}
- // close connection
- lws_http_transaction_completed(wsi);
- break;
- }
- //The following callbacks are ignored due to not being used
- case LWS_CALLBACK_LOCK_POLL:
- /*
- * lock mutex to protect pollfd state
- * called before any other POLL related callback
- * if protecting wsi lifecycle change, len == 1
- */
- break;
- case LWS_CALLBACK_UNLOCK_POLL:
- /*
- * unlock mutex to protect pollfd state when
- * called after any other POLL related callback
- * if protecting wsi lifecycle change, len == 1
- */
- break;
- case LWS_CALLBACK_GET_THREAD_ID:
- break;
- case LWS_CALLBACK_PROTOCOL_INIT:
- break;
- //If something unexpected pops up
- default:
- printf("unhandled callback %d\n ", reason);
- break;
- }
- return 0;
- }
- char *randstring(int length) {
- static int mySeed = 25011984;
- char *string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.-#'?!";
- size_t stringLen = strlen(string);
- char *randomString = NULL;
- srand((unsigned int)time(NULL) * length + ++mySeed);
- if (length < 1) {
- length = 1;
- }
- randomString = (char *)malloc(sizeof(char) * (length + 1));
- if (randomString) {
- short key = 0;
- for (int n = 0; n < length; n++) {
- key = rand() % stringLen;
- randomString[n] = string[key];
- }
- randomString[length] = '\0';
- return randomString;
- }
- else {
- printf("No memory");
- exit(1);
- }
- }
- const int replySize = 30000;
- char *reply_string = randstring(replySize);
- /* *
- * websocket_write_back: write the string data to the destination wsi.
- */
- int websocket_write_back(struct lws *wsi_in, char *str, int str_size_in)
- {
- //if (str == NULL || wsi_in == NULL)
- // return -1;
- int n;
- int len;
- unsigned char *out = NULL;
- char *write_what = reply_string;
- //if (str_size_in < 1)
- len = strlen(write_what);
- //else
- //len = str_size_in;
- out = (unsigned char *)malloc(sizeof(char)*(LWS_SEND_BUFFER_PRE_PADDING + len + LWS_SEND_BUFFER_POST_PADDING));
- //* setup the buffer*/
- memcpy(out + LWS_SEND_BUFFER_PRE_PADDING, write_what, len);
- //* write out*/
- n = lws_write(wsi_in, out + LWS_SEND_BUFFER_PRE_PADDING, len, LWS_WRITE_TEXT);
- //printf(KBLU"[websocket_write_back] %s\n"RESET, write_what);
- //* free the buffer*/
- free(out);
- return n;
- }
- static int ws_service_callback(
- struct lws *wsi,
- enum lws_callback_reasons reason,
- void *user,
- void *in, size_t len)
- {
- printf("Got a ws request %d\n", reason);
- switch (reason) {
- case LWS_CALLBACK_ESTABLISHED:
- printf(KYEL"[Main Service] Connection established\n"RESET);
- break;
- //* If receive a data from client*/
- case LWS_CALLBACK_RECEIVE:
- printf(KCYN_L"[Main Service] Server recvived:\n"RESET/*, (char *)in*/);
- //* echo back to client*/
- websocket_write_back(wsi, (char *)in, -1);
- break;
- case LWS_CALLBACK_CLOSED:
- printf(KYEL"[Main Service] Client close.\n"RESET);
- break;
- default:
- break;
- }
- return 0;
- }
- struct per_session_data {
- int fd;
- };
- bool got_sighup = false;
- bool got_sigint = false;
- void handle_signal(int signal) {
- switch (signal) {
- #ifdef _WIN32
- case SIGTERM:
- case SIGABRT:
- case SIGBREAK:
- #else
- case SIGHUP:
- #endif
- got_sighup = true;
- break;
- case SIGINT:
- got_sigint = true;
- break;
- }
- }
- #ifdef _WIN32
- void usleep(__int64 usec)
- {
- HANDLE timer;
- LARGE_INTEGER ft;
- ft.QuadPart = -(10 * usec); // Convert to 100 nanosecond interval, negative value indicates relative time
- timer = CreateWaitableTimer(NULL, TRUE, NULL);
- SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0);
- WaitForSingleObject(timer, INFINITE);
- CloseHandle(timer);
- }
- #endif
- struct per_session_data__http {
- lws_filefd_type fd;
- char post_string[256];
- #ifdef LWS_WITH_CGI
- struct lws_cgi_args args;
- #endif
- #if defined(LWS_WITH_CGI) || !defined(LWS_NO_CLIENT)
- int reason_bf;
- #endif
- unsigned int client_finished : 1;
- };
- static struct lws_protocols protocols[] = {
- /* first protocol must always be HTTP handler */
- {
- "http-only", /* name */
- callback_http, /* callback */
- sizeof(struct per_session_data__http), /* per_session_data_size */
- 0, /* max frame size / rx buffer */
- },
- {
- "tspp",
- ws_service_callback,
- sizeof(struct per_session_data),
- 0, /* rx buf size must be >= permessage-deflate rx size */
- },
- { NULL, NULL, 0, 0 } /* terminator */
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- // server url will usd port 5000
- int port = 5000;
- const char *interface = NULL;
- struct lws_context_creation_info info;
- struct lws_context *context;
- // Not using ssl
- const char *cert_path = NULL;
- const char *key_path = NULL;
- // no special options
- int opts = 0;
- #ifdef _WIN32
- signal(SIGINT, handle_signal);
- signal(SIGTERM, handle_signal);
- signal(SIGABRT, handle_signal);
- #else
- //* register the signal SIGINT handler */
- struct sigaction act;
- act.sa_handler = INT_HANDLER;
- act.sa_flags = 0;
- sigemptyset(&act.sa_mask);
- sigaction(SIGINT, &act, 0);
- #endif
- //* setup websocket protocol */
- //* setup websocket context info*/
- memset(&info, 0, sizeof info);
- info.port = port;
- info.iface = interface;
- info.protocols = protocols;
- info.extensions = lws_get_internal_extensions();
- info.ssl_cert_filepath = cert_path;
- info.ssl_private_key_filepath = key_path;
- info.gid = -1;
- info.uid = -1;
- info.options = opts;
- //* create libwebsocket context. */
- context = lws_create_context(&info);
- if (context == NULL) {
- printf(KRED"[Main] Websocket context create error.\n"RESET);
- return -1;
- }
- printf(KGRN"[Main] Websocket context create success.\n"RESET);
- //* websocket service */
- while (!destroy_flag) {
- lws_service(context, 0);
- }
- usleep(10);
- lws_context_destroy(context);
- return 0;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement