Skip to content

Commit 874788a

Browse files
committed
start
1 parent 34c724f commit 874788a

8 files changed

+352
-0
lines changed

.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,7 @@
3030
*.exe
3131
*.out
3232
*.app
33+
34+
/server/.vs
35+
/server/server/x64
36+
/server/x64

server/main.cpp

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#include "server.h"
2+
#include <iostream>
3+
4+
int main() try {
5+
HTTPServer server(8080);
6+
server.start();
7+
return 0;
8+
}
9+
catch (const std::exception& e) {
10+
std::cerr << "Error: " << e.what() << '\n';
11+
return 1;
12+
}

server/server.cpp

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
#include "server.h"
2+
#include <iostream>
3+
#include <stdexcept>
4+
5+
#ifdef _WIN32
6+
#include <ws2tcpip.h>
7+
#pragma comment(lib, "ws2_32.lib")
8+
#define CLOSE_SOCKET closesocket
9+
#else
10+
#include <sys/socket.h>
11+
#include <netinet/in.h>
12+
#include <unistd.h>
13+
#define INVALID_SOCKET -1
14+
#define SOCKET_ERROR -1
15+
#define CLOSE_SOCKET close
16+
#endif
17+
18+
HTTPServer::HTTPServer(uint16_t port) : port(port) {
19+
initializeWSA();
20+
21+
server_socket = socket(AF_INET, SOCK_STREAM, 0);
22+
if (server_socket == INVALID_SOCKET) {
23+
cleanupWSA();
24+
throw std::runtime_error("Socket creation failed");
25+
}
26+
27+
sockaddr_in address{};
28+
address.sin_family = AF_INET;
29+
address.sin_addr.s_addr = INADDR_ANY;
30+
address.sin_port = htons(port);
31+
32+
if (bind(server_socket, reinterpret_cast<sockaddr*>(&address), sizeof(address)) == SOCKET_ERROR) {
33+
CLOSE_SOCKET(server_socket);
34+
cleanupWSA();
35+
throw std::runtime_error("Bind failed");
36+
}
37+
}
38+
39+
HTTPServer::~HTTPServer() {
40+
CLOSE_SOCKET(server_socket);
41+
cleanupWSA();
42+
}
43+
44+
void HTTPServer::start() {
45+
if (listen(server_socket, SOMAXCONN) == SOCKET_ERROR) {
46+
throw std::runtime_error("Listen failed");
47+
}
48+
49+
std::cout << "Server running on port " << port << "\n";
50+
51+
while (true) {
52+
socket_t client = accept(server_socket, nullptr, nullptr);
53+
if (client == INVALID_SOCKET) continue;
54+
handleClient(client);
55+
}
56+
}
57+
58+
void HTTPServer::handleClient(socket_t client) {
59+
char buffer[1024]{};
60+
#ifdef _WIN32
61+
recv(client, buffer, sizeof(buffer), 0);
62+
#else
63+
read(client, buffer, sizeof(buffer));
64+
#endif
65+
66+
std::string request(buffer);
67+
if (request.find("GET / HTTP") != std::string::npos) {
68+
std::string response = createResponse();
69+
#ifdef _WIN32
70+
send(client, response.c_str(), static_cast<int>(response.length()), 0);
71+
#else
72+
write(client, response.c_str(), response.length());
73+
#endif
74+
}
75+
76+
CLOSE_SOCKET(client);
77+
}
78+
79+
std::string HTTPServer::createResponse() const {
80+
return "HTTP/1.1 200 OK\r\n"
81+
"Content-Type: application/json\r\n"
82+
"Connection: close\r\n\r\n"
83+
"{\"message\": \"hello world\"}";
84+
}
85+
86+
void HTTPServer::initializeWSA() {
87+
#ifdef _WIN32
88+
WSADATA wsaData;
89+
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
90+
throw std::runtime_error("WSAStartup failed");
91+
}
92+
#endif
93+
}
94+
95+
void HTTPServer::cleanupWSA() {
96+
#ifdef _WIN32
97+
WSACleanup();
98+
#endif
99+
}

server/server.h

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#pragma once
2+
3+
#include <cstdint>
4+
#include <string>
5+
6+
#ifdef _WIN32
7+
#include <winsock2.h>
8+
using socket_t = SOCKET;
9+
#else
10+
using socket_t = int;
11+
#endif
12+
13+
class HTTPServer {
14+
public:
15+
explicit HTTPServer(uint16_t port);
16+
~HTTPServer();
17+
18+
void start();
19+
20+
HTTPServer(const HTTPServer&) = delete;
21+
HTTPServer& operator=(const HTTPServer&) = delete;
22+
23+
private:
24+
void initializeWSA();
25+
void cleanupWSA();
26+
void handleClient(socket_t client);
27+
std::string createResponse() const;
28+
29+
socket_t server_socket;
30+
const uint16_t port;
31+
};

server/server.sln

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.11.35327.3
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "server", "server.vcxproj", "{0D472C47-19DC-4254-933A-CEBB76A8A5D8}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|x64 = Debug|x64
11+
Debug|x86 = Debug|x86
12+
Release|x64 = Release|x64
13+
Release|x86 = Release|x86
14+
EndGlobalSection
15+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
16+
{0D472C47-19DC-4254-933A-CEBB76A8A5D8}.Debug|x64.ActiveCfg = Debug|x64
17+
{0D472C47-19DC-4254-933A-CEBB76A8A5D8}.Debug|x64.Build.0 = Debug|x64
18+
{0D472C47-19DC-4254-933A-CEBB76A8A5D8}.Debug|x86.ActiveCfg = Debug|Win32
19+
{0D472C47-19DC-4254-933A-CEBB76A8A5D8}.Debug|x86.Build.0 = Debug|Win32
20+
{0D472C47-19DC-4254-933A-CEBB76A8A5D8}.Release|x64.ActiveCfg = Release|x64
21+
{0D472C47-19DC-4254-933A-CEBB76A8A5D8}.Release|x64.Build.0 = Release|x64
22+
{0D472C47-19DC-4254-933A-CEBB76A8A5D8}.Release|x86.ActiveCfg = Release|Win32
23+
{0D472C47-19DC-4254-933A-CEBB76A8A5D8}.Release|x86.Build.0 = Release|Win32
24+
EndGlobalSection
25+
GlobalSection(SolutionProperties) = preSolution
26+
HideSolutionNode = FALSE
27+
EndGlobalSection
28+
GlobalSection(ExtensibilityGlobals) = postSolution
29+
SolutionGuid = {0464BE79-74DD-4B6C-A56B-1C549350E642}
30+
EndGlobalSection
31+
EndGlobal

server/server.vcxproj

+141
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<ItemGroup Label="ProjectConfigurations">
4+
<ProjectConfiguration Include="Debug|Win32">
5+
<Configuration>Debug</Configuration>
6+
<Platform>Win32</Platform>
7+
</ProjectConfiguration>
8+
<ProjectConfiguration Include="Release|Win32">
9+
<Configuration>Release</Configuration>
10+
<Platform>Win32</Platform>
11+
</ProjectConfiguration>
12+
<ProjectConfiguration Include="Debug|x64">
13+
<Configuration>Debug</Configuration>
14+
<Platform>x64</Platform>
15+
</ProjectConfiguration>
16+
<ProjectConfiguration Include="Release|x64">
17+
<Configuration>Release</Configuration>
18+
<Platform>x64</Platform>
19+
</ProjectConfiguration>
20+
</ItemGroup>
21+
<PropertyGroup Label="Globals">
22+
<VCProjectVersion>17.0</VCProjectVersion>
23+
<Keyword>Win32Proj</Keyword>
24+
<ProjectGuid>{0d472c47-19dc-4254-933a-cebb76a8a5d8}</ProjectGuid>
25+
<RootNamespace>server</RootNamespace>
26+
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
27+
</PropertyGroup>
28+
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
29+
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
30+
<ConfigurationType>Application</ConfigurationType>
31+
<UseDebugLibraries>true</UseDebugLibraries>
32+
<PlatformToolset>v143</PlatformToolset>
33+
<CharacterSet>Unicode</CharacterSet>
34+
</PropertyGroup>
35+
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
36+
<ConfigurationType>Application</ConfigurationType>
37+
<UseDebugLibraries>false</UseDebugLibraries>
38+
<PlatformToolset>v143</PlatformToolset>
39+
<WholeProgramOptimization>true</WholeProgramOptimization>
40+
<CharacterSet>Unicode</CharacterSet>
41+
</PropertyGroup>
42+
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
43+
<ConfigurationType>Application</ConfigurationType>
44+
<UseDebugLibraries>true</UseDebugLibraries>
45+
<PlatformToolset>v143</PlatformToolset>
46+
<CharacterSet>Unicode</CharacterSet>
47+
</PropertyGroup>
48+
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
49+
<ConfigurationType>Application</ConfigurationType>
50+
<UseDebugLibraries>false</UseDebugLibraries>
51+
<PlatformToolset>v143</PlatformToolset>
52+
<WholeProgramOptimization>true</WholeProgramOptimization>
53+
<CharacterSet>Unicode</CharacterSet>
54+
</PropertyGroup>
55+
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
56+
<ImportGroup Label="ExtensionSettings">
57+
</ImportGroup>
58+
<ImportGroup Label="Shared">
59+
</ImportGroup>
60+
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
61+
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
62+
</ImportGroup>
63+
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
64+
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
65+
</ImportGroup>
66+
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
67+
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
68+
</ImportGroup>
69+
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
70+
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
71+
</ImportGroup>
72+
<PropertyGroup Label="UserMacros" />
73+
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
74+
<ClCompile>
75+
<WarningLevel>Level3</WarningLevel>
76+
<SDLCheck>true</SDLCheck>
77+
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
78+
<ConformanceMode>true</ConformanceMode>
79+
</ClCompile>
80+
<Link>
81+
<SubSystem>Console</SubSystem>
82+
<GenerateDebugInformation>true</GenerateDebugInformation>
83+
</Link>
84+
</ItemDefinitionGroup>
85+
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
86+
<ClCompile>
87+
<WarningLevel>Level3</WarningLevel>
88+
<FunctionLevelLinking>true</FunctionLevelLinking>
89+
<IntrinsicFunctions>true</IntrinsicFunctions>
90+
<SDLCheck>true</SDLCheck>
91+
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
92+
<ConformanceMode>true</ConformanceMode>
93+
</ClCompile>
94+
<Link>
95+
<SubSystem>Console</SubSystem>
96+
<EnableCOMDATFolding>true</EnableCOMDATFolding>
97+
<OptimizeReferences>true</OptimizeReferences>
98+
<GenerateDebugInformation>true</GenerateDebugInformation>
99+
</Link>
100+
</ItemDefinitionGroup>
101+
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
102+
<ClCompile>
103+
<WarningLevel>Level3</WarningLevel>
104+
<SDLCheck>true</SDLCheck>
105+
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
106+
<ConformanceMode>true</ConformanceMode>
107+
<LanguageStandard>stdcpp20</LanguageStandard>
108+
</ClCompile>
109+
<Link>
110+
<SubSystem>Console</SubSystem>
111+
<GenerateDebugInformation>true</GenerateDebugInformation>
112+
</Link>
113+
</ItemDefinitionGroup>
114+
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
115+
<ClCompile>
116+
<WarningLevel>Level3</WarningLevel>
117+
<FunctionLevelLinking>true</FunctionLevelLinking>
118+
<IntrinsicFunctions>true</IntrinsicFunctions>
119+
<SDLCheck>true</SDLCheck>
120+
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
121+
<ConformanceMode>true</ConformanceMode>
122+
</ClCompile>
123+
<Link>
124+
<SubSystem>Console</SubSystem>
125+
<EnableCOMDATFolding>true</EnableCOMDATFolding>
126+
<OptimizeReferences>true</OptimizeReferences>
127+
<GenerateDebugInformation>true</GenerateDebugInformation>
128+
<AdditionalDependencies>ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
129+
</Link>
130+
</ItemDefinitionGroup>
131+
<ItemGroup>
132+
<ClCompile Include="main.cpp" />
133+
<ClCompile Include="server.cpp" />
134+
</ItemGroup>
135+
<ItemGroup>
136+
<ClInclude Include="server.h" />
137+
</ItemGroup>
138+
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
139+
<ImportGroup Label="ExtensionTargets">
140+
</ImportGroup>
141+
</Project>

server/server.vcxproj.filters

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<ItemGroup>
4+
<Filter Include="Source Files">
5+
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
6+
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
7+
</Filter>
8+
<Filter Include="Header Files">
9+
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
10+
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
11+
</Filter>
12+
<Filter Include="Resource Files">
13+
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
14+
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
15+
</Filter>
16+
</ItemGroup>
17+
<ItemGroup>
18+
<ClCompile Include="server.cpp">
19+
<Filter>Source Files</Filter>
20+
</ClCompile>
21+
<ClCompile Include="main.cpp">
22+
<Filter>Source Files</Filter>
23+
</ClCompile>
24+
</ItemGroup>
25+
<ItemGroup>
26+
<ClInclude Include="server.h">
27+
<Filter>Source Files</Filter>
28+
</ClInclude>
29+
</ItemGroup>
30+
</Project>

server/server.vcxproj.user

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<PropertyGroup />
4+
</Project>

0 commit comments

Comments
 (0)