-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.c
132 lines (106 loc) · 2.71 KB
/
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <libwebsockets.h>
#include <string.h>
#include <stdio.h>
static int callback_http( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len )
{
switch( reason )
{
char* uri;
char* ext;
const char* mime;
case LWS_CALLBACK_HTTP:
uri = (char*) in;
if(strlen(uri) < 2){
uri = "fileupload.html";
}else{
uri = uri + 1;
}
ext = strrchr(uri, '.');
printf("requested in: %s, uri: %s, ext: %s\n", in, uri, ext);
mime = "text/html";
if(!strcmp(ext, ".js")){
mime = "application/javascript";
}
lws_serve_http_file( wsi, uri, mime, NULL, 0 );
break;
default:
break;
}
return 0;
}
#define EXAMPLE_RX_BUFFER_BYTES (102400)
struct payload
{
unsigned char data[LWS_SEND_BUFFER_PRE_PADDING + EXAMPLE_RX_BUFFER_BYTES + LWS_SEND_BUFFER_POST_PADDING];
size_t len;
} received_payload;
int file_state = 0;
FILE* fp;
static int callback_example( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len )
{
switch( reason )
{
case LWS_CALLBACK_RECEIVE:
memcpy( &received_payload.data[LWS_SEND_BUFFER_PRE_PADDING], in, len );
received_payload.len = len;
lws_callback_on_writable_all_protocol( lws_get_context( wsi ), lws_get_protocol( wsi ) );
break;
case LWS_CALLBACK_SERVER_WRITEABLE:
//lws_write( wsi, &received_payload.data[LWS_SEND_BUFFER_PRE_PADDING], received_payload.len, LWS_WRITE_TEXT );
if(!lws_frame_is_binary(wsi)){
if(file_state == 0){
fp = fopen("transferred.data", "wb");
file_state = 1;
}else if(file_state == 1){
fclose(fp);
file_state = 0;
}
} else{
fwrite(&received_payload.data[LWS_SEND_BUFFER_PRE_PADDING],
sizeof(char), received_payload.len, fp);
}
break;
default:
break;
}
return 0;
}
enum protocols
{
PROTOCOL_HTTP = 0,
PROTOCOL_EXAMPLE,
PROTOCOL_COUNT
};
static struct lws_protocols protocols[] =
{
/* The first protocol must always be the HTTP handler */
{
"http-only", /* name */
callback_http, /* callback */
0, /* No per session data. */
0, /* max frame size / rx buffer */
},
{
"example-protocol",
callback_example,
0,
EXAMPLE_RX_BUFFER_BYTES,
},
{ NULL, NULL, 0, 0 } /* terminator */
};
int main( int argc, char *argv[] )
{
struct lws_context_creation_info info;
memset( &info, 0, sizeof(info) );
info.port = 8000;
info.protocols = protocols;
info.gid = -1;
info.uid = -1;
struct lws_context *context = lws_create_context( &info );
while( 1 )
{
lws_service( context, /* timeout_ms = */ 1000000 );
}
lws_context_destroy( context );
return 0;
}