I am trying to receive the data from a websocket client and send back some data. I was successful with the former but got "Segmentation fault" error with the later especially adding this line got me stuck
lws_write(wsi, "thank you", strlen("thank you"), LWS_WRITE_TEXT);
Following is the complete code
include
include
include
static int callback_websockets(struct lws wsi, enum lws_callback_reasons reason, void user, void in, size_t len)
{
switch (reason)
{
case LWS_CALLBACK_RECEIVE:
printf("Received message from client: %.s\n", (int)len, (char *)in);
// Send "thank you" as a response
lws_write(wsi, "thank you", strlen("thank you"), LWS_WRITE_TEXT);
break;
case LWS_CALLBACK_ESTABLISHED:
printf("Client connected\n");
// Perform actions when a client establishes a connection
break;
case LWS_CALLBACK_CLOSED:
printf("Client disconnected\n");
// Perform actions when a client disconnects
break;
default:
// Handle other callback reasons if necessary
break;
}
I am trying to receive the data from a websocket client and send back some data. I was successful with the former but got "Segmentation fault" error with the later especially adding this line got me stuck lws_write(wsi, "thank you", strlen("thank you"), LWS_WRITE_TEXT);
Following is the complete code
include
include
include
static int callback_websockets(struct lws wsi, enum lws_callback_reasons reason, void user, void in, size_t len) { switch (reason) { case LWS_CALLBACK_RECEIVE: printf("Received message from client: %.s\n", (int)len, (char *)in);
case LWS_CALLBACK_ESTABLISHED: printf("Client connected\n"); // Perform actions when a client establishes a connection break;
case LWS_CALLBACK_CLOSED: printf("Client disconnected\n"); // Perform actions when a client disconnects break;
default: // Handle other callback reasons if necessary break; }
return 0; }
static struct lws_protocols protocols[] = { {"websockets", callback_websockets, 0, 0}, {NULL, NULL, 0, 0}};
int main(int argc, char *argv[]) { struct lws_context_creation_info info; memset(&info, 0, sizeof(info));
info.port = 3000; info.protocols = protocols; info.gid = -1; info.uid = -1;
struct lws_context *context = lws_create_context(&info);
if (!context) { fprintf(stderr, "Error creating libwebsockets context\n"); return -1; }
printf("WebSocket server started on port %d...\n", info.port);
while (1) { lws_service(context, 50); // Add other background tasks or conditions for breaking out of the loop }
lws_context_destroy(context);
return 0; };