#include "pch.h"
#if defined(_MSC_VER) || defined(__MINGW32__) || defined(WIN32)
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <windows.h>
#define close closesocket
#pragma comment(lib, "ws2_32.lib")
class WinSockInit
{
WSADATA _wsa;
public:
WinSockInit()
{
WSAStartup(MAKEWORD(2, 0), &_wsa);
}
~WinSockInit()
{
WSACleanup();
}
};
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include <iostream>
#include <string>
using namespace std;
void UrlRouter(int clientSock, string const & url)
{
string hint;
if (url == "/")
{
cout << url << " 收到資訊\n";
hint = "haha, this is home page!";
send(clientSock, hint.c_str(), hint.length(), 0);
}
else if (url == "/hello")
{
cout << url << " 收到資訊\n";
hint = "你好!";
send(clientSock, hint.c_str(), hint.length(), 0);
}
else
{
cout << url << " 收到資訊\n";
hint = "未定義URL!";
send(clientSock, hint.c_str(), hint.length(), 0);
}
}
int main()
{
#if defined(_MSC_VER) || defined(__MINGW32__) || defined(WIN32)
WinSockInit socklibInit;
#endif
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in addr = { 0 };
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(8090);
int rc;
rc = bind(sock, (sockaddr*)&addr, sizeof(addr));
rc = listen(sock, 0);
sockaddr_in clientAddr;
int clientAddrSize = sizeof(clientAddr);
int clientSock;
while (-1 != (clientSock = accept(sock, (sockaddr*)&clientAddr, (socklen_t*)&clientAddrSize)))
{
string requestStr;
int bufSize = 4096;
requestStr.resize(bufSize);
recv(clientSock, &requestStr[0], bufSize, 0);
string firstLine = requestStr.substr(0, requestStr.find("\r\n"));
firstLine = firstLine.substr(firstLine.find(" ") + 1);
string url = firstLine.substr(0, firstLine.find(" "));
string response =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=gbk\r\n"
"Connection: close\r\n"
"\r\n";
send(clientSock, response.c_str(), response.length(), 0);
UrlRouter(clientSock, url);
close(clientSock);
}
close(sock);
return 0;
}