-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws_server.c
72 lines (57 loc) · 1.35 KB
/
ws_server.c
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
#include "csocket.h"
#define LIST_SIZE 32
int list[LIST_SIZE];
int list_count = 0;
int list_insert(int value) {
int i;
for (i=0; i<LIST_SIZE; i++) {
if (list[i] == 0) {
list[i] = value;
list_count++;
return 1;
}
}
return 0;
}
int list_remove(int value) {
int i;
for (i=0; i<LIST_SIZE; i++) {
if (list[i] == value) {
list[i] = 0;
list_count--;
return 1;
}
}
return 0;
}
int on_header(char *name, char *value, void *userdata) {
int sock = *(int*)userdata;
if (strcmp(name, "Sec-WebSocket-Key") == 0) {
csocket_ws_handshake_as_server(sock, value);
return 1;
}
return 0;
}
void on_request(int sock) {
char buffer[2048], *method, *path, *headers, *body;
int i, ret;
memset(buffer, 0, sizeof(buffer));
csocket_read(sock, buffer, sizeof(buffer)-1);
csocket_parse_request(buffer, &method, &path, &headers, &body);
if (csocket_parse_headers(headers, on_header, &sock) != 1) return;
printf("new socket: %i\n", sock);
list_insert(sock);
do {
memset(buffer, 0, sizeof(buffer));
ret = csocket_ws_read(sock, buffer, sizeof(buffer)-1);
for (i=0; i<list_count; i++) {
printf("broadcasting '%s' to: %i\n", buffer, list[i]);
csocket_ws_write(list[i], 1, 0x1, buffer, strlen(buffer), 0);
}
} while(ret > 0);
list_remove(sock);
}
int main(void) {
csocket_listen("localhost", 80, on_request);
return 0;
}