Game Development Reference
In-Depth Information
Getting ready
Writing an HTTP server from scratch is not easy, so we use a freely available simple server by
René Nyffenegger from the following web page:
http://www.adp-gmbh.ch/win/misc/
webserver.html
.
We use most of these sources directly, and our more or less reined version which supports
Android is included in the
App5
example. The most important difference from the original is
the usage of an abstract socket API built on top of WinSock and Android BSD sockets.
We recommend that you take a closer look at the
Sockets.h
and
Sockets.cpp
iles in
the
App5
sources.
How to do it…
1.
The HTTP server is started on a separate thread, which is a descendant of the
iThread
class. The main loop of the server is simple:
while ( !IsPendingExit() )
{
LTCPSocket* NewSocket = in->Accept();
if ( NewSocket != 0 )
{
// Add new thread
HTTPRequestThread* T = new HTTPRequestThread();
T->FServer = this;
T->FSocket = NewSocket;
T->Start();
}
}
2.
We await an incoming connection, and when the
Accept()
method succeeds,
a new
HTTPRequestThread
is started. This thread reads data from the newly
created socket and ills in the
sHTTPServerRequest
structure.
Finally, this request is handled in the
HandleRequest()
method by illing the
sHTTPServerRequest::FData
ield with the content of an HTML page. In the end,
this data is sent to the client. The code is linear, but a little lengthy to present it here.
We refer the reader to the
HTTP.cpp
ile for the details.
How it works…
To utilize the server, we have created the
HTTPServerThread
instance and provided an
implementation of the
SetVariableValue()
and
GetVariableValue()
functions in
the
HTTP.cpp
ile, which are empty by default. The server startup code is located in the
OnStart()
function.