Enhance WebSocket handling: remove socket timeout, improve frame creation, and update test page UI

This commit is contained in:
2025-12-11 21:08:15 +01:00
parent 5d32e8c2e0
commit 71c0670d7f
3 changed files with 456 additions and 252 deletions

View File

@@ -536,6 +536,12 @@ static void *handle_websocket(void *arg)
pthread_exit(NULL);
}
// Remove socket timeout for WebSocket (connections should stay open)
struct timeval ws_timeout;
ws_timeout.tv_sec = 0; // No timeout - wait indefinitely
ws_timeout.tv_usec = 0;
setsockopt(conn->socket_fd, SOL_SOCKET, SO_RCVTIMEO, &ws_timeout, sizeof(ws_timeout));
log_event("WebSocket connection established");
uint8_t buffer[65536];
@@ -554,9 +560,13 @@ static void *handle_websocket(void *arg)
if (bytes_received <= 0)
{
ws_close_connection(conn, 1000);
free(conn);
pthread_exit(NULL);
if (bytes_received == 0 || (errno != EAGAIN && errno != EWOULDBLOCK))
{
ws_close_connection(conn, 1000);
free(conn);
pthread_exit(NULL);
}
continue;
}
ws_frame_header_t header;
@@ -578,7 +588,7 @@ static void *handle_websocket(void *arg)
if (ws_is_valid_utf8(payload, header.payload_length))
{
// Echo back the text message
ws_send_text(conn, (const char *)payload);
ws_send_frame(conn, WS_OPCODE_TEXT, payload, header.payload_length);
log_event("WebSocket text frame received and echoed");
}
else

View File

@@ -219,6 +219,28 @@ int ws_parse_frame(const uint8_t *data, size_t len, ws_frame_header_t *header, u
// Create WebSocket frame
int ws_create_frame(uint8_t *buffer, size_t buffer_size, uint8_t opcode, const uint8_t *payload, size_t payload_len)
{
size_t header_size;
// Calculate total frame size first
if (payload_len < 126)
{
header_size = 2;
}
else if (payload_len < 65536)
{
header_size = 4;
}
else
{
header_size = 10;
}
// Check buffer size before writing anything
if (buffer_size < header_size + payload_len)
{
return -1;
}
size_t offset = 0;
// First byte: FIN + opcode
@@ -227,22 +249,16 @@ int ws_create_frame(uint8_t *buffer, size_t buffer_size, uint8_t opcode, const u
// Second byte: MASK + payload length
if (payload_len < 126)
{
if (buffer_size < offset + 1 + payload_len)
return -1;
buffer[offset++] = payload_len;
buffer[offset++] = (uint8_t)payload_len;
}
else if (payload_len < 65536)
{
if (buffer_size < offset + 3 + payload_len)
return -1;
buffer[offset++] = 126;
buffer[offset++] = (payload_len >> 8) & 0xFF;
buffer[offset++] = payload_len & 0xFF;
}
else
{
if (buffer_size < offset + 9 + payload_len)
return -1;
buffer[offset++] = 127;
for (int i = 7; i >= 0; i--)
{
@@ -257,7 +273,7 @@ int ws_create_frame(uint8_t *buffer, size_t buffer_size, uint8_t opcode, const u
offset += payload_len;
}
return offset;
return (int)offset;
}
// Send WebSocket frame