77//
88
99#include " config.h"
10+ #include < runtime/JSONObject.h>
11+ #include < runtime/LiteralParser.h>
1012#include " SimpleTCPServer.h"
13+ #include < string>
1114
1215// auto-generated file with ragel
1316#include " http_state.c"
@@ -18,20 +21,25 @@ SimpleTCPServer::SimpleTCPServer(int port)
1821{
1922 struct hostent *hp;
2023 struct sockaddr_in sa;
21-
24+
2225 printf (" starting tcp server on port %d\n " , port);
23-
26+
2427 memset (&sa, 0 , sizeof (struct sockaddr_in ));
2528 // listen all
2629 hp = gethostbyname (" 0.0.0.0" );
2730 ASSERT (hp);
28-
31+
2932 sa.sin_port = htons (port);
3033 sa.sin_family = hp->h_addrtype ;
31-
34+
3235 m_socket = socket (AF_INET, SOCK_STREAM, 0 );
3336 ASSERT (m_socket > 0 );
34-
37+
38+ int on = 1 ;
39+ int res = setsockopt (m_socket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on));
40+ (void )res;
41+ ASSERT (res == 0 );
42+
3543 if (bind (m_socket, (const struct sockaddr *)&sa, sizeof (struct sockaddr_in )) < 0 ) {
3644 close (m_socket);
3745 ASSERT (0 );
@@ -45,6 +53,10 @@ SimpleTCPServer::~SimpleTCPServer()
4553
4654void SimpleTCPServer::gotHeader (const char *name, const char *value)
4755{
56+ std::string key (name);
57+ if (key.compare (" Content-Length" ) == 0 ) {
58+ m_currentDataLength = atoi (value);
59+ }
4860 printf (" got key: '%s' ~> '%s'\n " , name, value);
4961}
5062
@@ -57,21 +69,17 @@ void SimpleTCPServer::start()
5769{
5870 listen (m_socket, 1 );
5971 int t;
60- if ((t = accept (m_socket, NULL , NULL )) > 0 ) {
72+ while ((t = accept (m_socket, NULL , NULL )) > 0 ) {
6173 // we got something, process...
62- char buff[128 ];
63- memset (buff, 0 , 128 );
64- int bytesRead = 0 ;
65- char *bodyPointer = (char *)buff;
66- while ((bytesRead = read (t, buff, 128 )) > 0 ) {
67- int parsedBytes = parseHeaders (buff, bytesRead, this );
68- if (parsedBytes > 0 ) {
69- bodyPointer += parsedBytes;
70- printf (" body: '%s'\n " , bodyPointer);
71- } else {
72- printf (" got an error...\n " );
73- printf (" %s\n " , buff);
74+ int parsed = parseHeaders (t, this );
75+ if (parsed && m_currentDataLength) {
76+ // parsed headers and actually got a body length, now read that body
77+ unsigned char *buff = (unsigned char *)calloc (m_currentDataLength + 1 , 1 );
78+ int bytesRead = read (t, buff, m_currentDataLength);
79+ while (bytesRead < m_currentDataLength) {
80+ bytesRead = read (t, buff + bytesRead, m_currentDataLength - bytesRead);
7481 }
82+ parseRequest (buff, m_currentDataLength);
7583 }
7684 }
7785}
0 commit comments