char buffer[BUFSIZE] = "65000";
const int PORT = 8080;
// run test
int main()
{
SocketCom myServer;
//cout << "Welcome to Eric Raymond's Web Server Application System" << endl;
//cout << "<Server> Attempting to listen on Port " << PORT << endl << endl;
//system("pause");
//Initialize myserver
int state = myServer.xInit(PORT);
while (TRUE)
{
//Listen on port 8080
myServer.xListen();
//resolve server address and port
SOCKET mySock = myServer.xAccept();
clientHandler(mySock, myServer);
myServer.xShutdown(mySock);
}
//clientHandler(mySock, myServer);
system("Pause");
return 0;
}
unsigned int clientHandler(SOCKET mySock, SocketCom &plist)
{
int i = 0;
string fileData, temp;
SocketCom * myObj = new SocketCom;
myObj->xRecv(mySock, buffer, BUFSIZE, 0);
string str1 = string(buffer); //get name of file
int pos0 = str1.find('/');
int pos1 = str1.find(' ', ++pos0);
int len = (pos1 - pos0);
string str2 = str1.substr(pos0, len);
fstream fileStream;
fileStream.open(str2);
if (!fileStream)
{
//favico.ico / double request block
unsigned int favico_ico = 9999;
if (str2 == "-9999")
exit(-9999); //exit code
if (str2 == "favicon.ico")/*kills the request for a favicon by the browser that would force 404 */
{
return favico_ico;
}
else // sends ok in order to send custom html instead of browser default 404
{
string badurl = "HTTP/1.0 200 OK\r\nDate: Tue 01 2016 Mar 17:01:00 GMT\r\n Content-Type: text/html\r\n Content-Length:";
cout << "Server sent message: Bad URL" << endl << endl;
fileData = "<html><body><h1>Oops! You broke it!</h1></body></html>";//404 message - force feed html code for custom message
unsigned long long len = fileData.length();
string slen = to_string(len);
badurl += slen + "\r\n\r\n";
badurl += fileData;
int r = myObj->xSend(mySock, &badurl[0], badurl.length(), 0);
}
}
else
{
string okStr = "HTTP/1.0 200 OK\r\nDate: Tue 01 2016 Mar 17:01:00 GMT\r\n Content-Type: text/html\r\n Content-Length:"; // change for dynamic time date? to allow images? audio clips?
cout << "Server sent message: " << okStr << endl;
while (!fileStream.eof())
{
getline(fileStream, temp, '\n');
fileData += temp + " ";
}
unsigned long long len = fileData.length();
string slen = to_string(len);
okStr += slen + "\r\n\r\n";
okStr += fileData;
int r = myObj->xSend(mySock, &okStr[0], okStr.length(), 0);
cout << fileData << endl << endl;