Created
January 27, 2023 13:15
-
-
Save leannejdong/f7653dac6000c7513dc194d2bb7bf292 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
#include <libwebsockets.h> | |
static int callback_example(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) | |
{ | |
switch (reason) { | |
case LWS_CALLBACK_ESTABLISHED: // just log message that someone is connecting | |
printf("connection established\n"); | |
break; | |
case LWS_CALLBACK_SERVER_WRITEABLE: | |
{ | |
char buffer[LWS_PRE + 100]; | |
char *p = &buffer[LWS_PRE]; | |
sprintf(p, "Hello from server"); | |
lws_write(wsi, (unsigned char *)p, strlen(p), LWS_WRITE_TEXT); | |
break; | |
} | |
default: | |
break; | |
} | |
return 0; | |
} | |
int main(void) | |
{ | |
struct lws_protocols protocols[] = { | |
{ | |
"example-protocol", | |
callback_example, | |
0, | |
100, | |
}, | |
{ NULL, NULL, 0, 0 } /* terminator */ | |
}; | |
struct lws_context_creation_info info; | |
memset(&info, 0, sizeof info); | |
info.port = 9000; | |
info.protocols = protocols; | |
struct lws_context *context = lws_create_context(&info); | |
while (1) { | |
lws_service(context, 50); | |
} | |
lws_context_destroy(context); | |
return 0; | |
} | |
/* | |
- Initialize the libwebsockets library by calling the lws_context_creation_info function and passing in the necessary parameters such as the server port and protocol. | |
- Create a callback function that will handle incoming connections and requests from clients. This function will be invoked whenever a new connection is established or data is received from a client. | |
- Start the server by calling the lws_initloop function and passing in the lws_context and the callback function. | |
- In the callback function, one can use the lws_write function to send data back to the client, and the lws_callback_on_writable function to enable writing to the socket. | |
- Once the server is running, clients can connect to it using a websocket library or by manually sending websocket handshake headers. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment