提交 a16f4cc4 编写于 作者: xc13262215230's avatar xc13262215230

cs386_httpclient在linux下测试

上级 24360c72
......@@ -27,6 +27,7 @@
#include<signal.h>
#include<sys/socket.h>
#include <net/if.h>
#include <netdb.h> // 处理编译错误:getaddrinfo找不到定义
#define SOCKET int
#define INVALID_SOCKET (SOCKET)(~0)
......
......@@ -92,14 +92,15 @@ g++ server.cpp -std=c++11 -pthread -o EasyServer
66.cs350_新增httpserver主动断开连接处理事件,httpclient继续下一次数据请求 072+
67.cs350_响应断线事件(服务端主动断线),(http客户端)请求不断 051+
68.cs351_给HTTPCLIENT增加一个消息请求队列 096+
69.cs352_httpclient新增POST请求流程 124+ [2023-3-19: 4924]
69.cs352_httpclient新增POST请求流程 124+ [2024-3-19: 4924]
70.cs353_处理数据访问越界BUG 015+
71.cs354_http传递json格式数据 095+
72.cs354_处理数据残留BUG 045+
73.[2024-4-2]cs_355调整httpclientc.hpp和httpclients.hpp 060+
74.[2024-4-2]cs_355调整httpclientc.hpp和httpclients.hpp 240+ [2024-4-17: 5439]
code lines sum -> 4924+
code lines sum -> 5439+
//===================================================================================================================
[注意:linux编译指令]
......@@ -889,6 +890,13 @@ httpclient和httpserver都有涉及。可以自行根据业务场景进行业务
162.最主流的通信协议:TCP、HTTP、WebSocket。到目前已经讲完Tcp和http连接。
当前网络通信引擎支持这三种通信协议。
163.[78-102章节-websocket暂时仅作了解]
1)Tcp协议,服务端和客户端连接后双方随时可向对端发送网络消息。
2)Http协议,仅支持客户端httpclient发送数据请求,服务端httpserver收到请求后发送数据应答。
164.c++14特性当前IDE不支持,visual studio 2013最大支持c++11标准。
......

// 三种网络通信模型,三选一
//#include "TcpSelectClient.hpp" // using select(both linux and windows)
#include "TcpSelectClient.hpp" // using select(both linux and windows)
//#include "TcpEpollClient.hpp" // using epoll(linux-only)
#include "TcpIocpClient.hpp" // using iocp(windows-only) 注意:若要采用IOCP,CELLBuffer.hpp的宏[CELL_USE_IOCP]要启用
//#include "TcpIocpClient.hpp" // using iocp(windows-only) 注意:若要采用IOCP,CELLBuffer.hpp的宏[CELL_USE_IOCP]要启用
#include "TimeStamp.hpp" // 分析:头文件名称区分大小写
#include "Config.hpp"
......@@ -46,7 +46,7 @@ int nRecvBuffSize = RECV_BUFF_SZIE;
int nCheckSendBack = true; // (true:启用(默认),false-不启用)
// TcpEpollClient TcpSelectClient TcpIocpClient
class MyClient : public TcpIocpClient // 网络通信模型具体采用: select or epoll or iocp
class MyClient : public TcpSelectClient // 网络通信模型具体采用: select or epoll or iocp
{
public:
MyClient()
......
......@@ -25,7 +25,7 @@ public:
char reqBuff[256] = { 0 };
if (i % 100 >= 66) { // [66, 99]
sprintf(reqBuff, "http://127.0.0.1:4568/add?a=%d&b=1", i);
sprintf(reqBuff, "http://192.168.56.1:4568/add?a=%d&b=1", i);
// para1: www.baidu.com/; para2: callback
this->Get(reqBuff, [this](HttpClientC* pHttpClient){ // lambda表达式作为实参
......@@ -44,7 +44,7 @@ public:
}
else if (i % 100 >= 33) { // [33, 66)
sprintf(reqBuff, "http://127.0.0.1:4568/sub?a=%d&b=1", i);
sprintf(reqBuff, "http://192.168.56.1:4568/sub?a=%d&b=1", i);
this->Get(reqBuff, [this](HttpClientC* pHttpClient){ // lambda表达式作为实参
if (pHttpClient != nullptr) { // httpclient正确收到应答消息场景
......@@ -63,7 +63,7 @@ public:
else { // [0, 33)
sprintf(reqBuff, "token=abc123&json={\"a2\":%d,\"b\":33 }", i);
this->Post("http://127.0.0.1:4568/jsonTest", reqBuff, [this](HttpClientC* pHttpClient){ // lambda表达式作为实参
this->Post("http://192.168.56.1:4568/jsonTest", reqBuff, [this](HttpClientC* pHttpClient){ // lambda表达式作为实参
if (pHttpClient != nullptr) { // httpclient正确收到应答消息场景
CELLLog_Info("[httpclient][Test] recv http web server json msg2 to way2: [bodyLen = %s] [id = %d].",
......@@ -110,9 +110,9 @@ int main(int argc, char* args[])
// 同时发起多个GET请求
// Get1
// 分析:?后面参数部分可以写json格式的字符串信息进行传输,但是特殊的字符要进行转码
// URL编码前: http://127.0.0.1:4568/add?{\"a\":3,\"b\":5} // json字符串格式参数,并采用在线URL工具编码后如下,
// URL编码前: http://192.168.56.1:4568/add?{\"a\":3,\"b\":5} // json字符串格式参数,并采用在线URL工具编码后如下,
// URL编码后: http%3A%2F%2F127.0.0.1%3A4568%2Fadd%3F%7B%5C%22a%5C%22%3A3%2C%5C%22b%5C%22%3A5%7D
httpClient.Post("http://127.0.0.1:4568/add?a=10&b=20", [&httpClient](HttpClientC* pHttpClient){ // lambda表达式作为实参
httpClient.Post("http://192.168.56.1:4568/add?a=10&b=20", [&httpClient](HttpClientC* pHttpClient){ // lambda表达式作为实参
CELLLog_Info("[httpclient] recv http web server msg1: \n");
auto responseStr = pHttpClient->Content();
CELLLog_Info("[Content=%s]\n", responseStr);
......@@ -120,7 +120,7 @@ int main(int argc, char* args[])
// 待优化点:相同的IP+PORT已经连接的,不用再次连接,直接发起数据请求。不用断开旧连接,重新建立连接,比较浪费系统资源。
// Get2
httpClient.Get("http://127.0.0.1:4568/add?a=11&b=22", [](HttpClientC* pHttpClient){ // lambda表达式作为实参
httpClient.Get("http://192.168.56.1:4568/add?a=11&b=22", [](HttpClientC* pHttpClient){ // lambda表达式作为实参
CELLLog_Info("[httpclient] recv http web server msg2: \n");
auto responseStr = pHttpClient->Content();
CELLLog_Info("[Content=%s]\n", responseStr);
......@@ -130,7 +130,7 @@ int main(int argc, char* args[])
// token-标识httpclient的身份ID,httpserver通过这个token来识别我,有效是有时限的,根据业务决定
// json-标准的json字符串
// 方式1
httpClient.Post("http://127.0.0.1:4568/jsonTest?token=abc123&json={\"a1\":100,\"b\":22}", [&httpClient](HttpClientC* pHttpClient){ // lambda表达式作为实参
httpClient.Post("http://192.168.56.1:4568/jsonTest?token=abc123&json={\"a1\":100,\"b\":22}", [&httpClient](HttpClientC* pHttpClient){ // lambda表达式作为实参
CELLLog_Info("[httpclient] recv http web server json msg1 to way1: \n");
auto responseStr = pHttpClient->Content();
CELLLog_Info("[Content=%s]\n", responseStr);
......@@ -139,13 +139,16 @@ int main(int argc, char* args[])
// 而是作为一个整体字符串存储就可以,如果将token写到json字符串内部,服务端收到消息收就必须对
// json字符串进行解析采用获取token数据,识别客户端的身份信息。
// 方式2
httpClient.Post("http://127.0.0.1:4568/jsonTest", "token=abc123&json={\"a2\":200,\"b\":33 }", [&httpClient](HttpClientC* pHttpClient){ // lambda表达式作为实参
httpClient.Post("http://192.168.56.1:4568/jsonTest", "token=abc123&json={\"a2\":200,\"b\":33 }", [&httpClient](HttpClientC* pHttpClient){ // lambda表达式作为实参
CELLLog_Info("[httpclient] recv http web server json msg2 to way2: \n");
auto responseStr = pHttpClient->Content();
CELLLog_Info("[Content=%s]\n", responseStr);
});
});
//httpClient.Get("https://www.baidu.com"); // 获取外网域名IP列表
......@@ -155,7 +158,7 @@ int main(int argc, char* args[])
//httpClient.Get("www.baidu.com");
//httpClient.Get("www.qq.com");
//httpClient.Get("http://ipv4.dosfu.com:4567/");
//httpClient.Get("http://127.0.0.1:4568/add?c=10&d=20");
//httpClient.Get("http://192.168.56.1:4568/add?c=10&d=20");
//httpClient.Get("ipv6.dosfu.com");
//httpClient.Get("dosfu.com");
......
......@@ -72,6 +72,7 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<None Include="..\..\bin\Debug\HelloHttp_HttpServer.sh" />
<None Include="..\..\bin\Debug\TcpEasyServer_linux_ipv4.sh" />
<None Include="config\WebEasyServer_wins_ipv4.bat" />
<None Include="www\html_test.html" />
......
......@@ -27,6 +27,9 @@
<None Include="..\..\bin\Debug\TcpEasyServer_linux_ipv4.sh">
<Filter>头文件</Filter>
</None>
<None Include="..\..\bin\Debug\HelloHttp_HttpServer.sh">
<Filter>头文件</Filter>
</None>
</ItemGroup>
<ItemGroup>
<ClCompile Include="server.cpp">
......
// openai or chatgpt to study
// [2024-4-17 to today]
//==== valid code calc ===//
UdpClient.hpp +039
UdpServer.hpp +059
1.UDP服务端和UDP客户端通信实例学习。
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\openai\debug\vc120.pdb
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\openai\debug\vc120.idb
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\openai\debug\ai.obj
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\debug\openai.ilk
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\debug\openai.exe
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\debug\openai.pdb
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\openai\debug\openai.tlog\cl.command.1.tlog
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\openai\debug\openai.tlog\cl.read.1.tlog
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\openai\debug\openai.tlog\cl.write.1.tlog
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\openai\debug\openai.tlog\link.command.1.tlog
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\openai\debug\openai.tlog\link.read.1.tlog
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\openai\debug\openai.tlog\link.write.1.tlog
生成启动时间为 2024/4/17 23:30:11。
1>项目“D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\OpenAI\OpenAI.vcxproj”在节点 2 上(Rebuild 个目标)。
1>ClCompile:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\CL.exe /c /ZI /nologo /W3 /WX- /Od /Oy- /D WIN32 /D _DEBUG /D _CONSOLE /D _LIB /D _UNICODE /D UNICODE /Gm /EHsc /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Fo"Debug\\" /Fd"Debug\vc120.pdb" /Gd /TP /analyze- /errorReport:prompt aimain.cpp
aimain.cpp
Link:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\link.exe /ERRORREPORT:PROMPT /OUT:"D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\Debug\OpenAI.exe" /INCREMENTAL /NOLOGO kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /MANIFEST /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /manifest:embed /DEBUG /PDB:"D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\Debug\OpenAI.pdb" /SUBSYSTEM:CONSOLE /TLBID:1 /DYNAMICBASE /NXCOMPAT /IMPLIB:"D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\Debug\OpenAI.lib" /MACHINE:X86 Debug\aimain.obj
OpenAI.vcxproj -> D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\Debug\OpenAI.exe
1>已完成生成项目“D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\OpenAI\OpenAI.vcxproj”(Rebuild 个目标)的操作。
生成成功。
已用时间 00:00:02.02
B^D:\C++CODE\ENGINE2.0研究\ENGINE2.0\ENGINE2.0\ENGINE2.0\OPENAI\AIMAIN.CPP
B^D:\C++CODE\ENGINE2.0研究\ENGINE2.0\ENGINE2.0\ENGINE2.0\OPENAI\AIMAIN.CPP
#TargetFrameworkVersion=v4.0:PlatformToolSet=v120:EnableManagedIncrementalBuild=false:VCToolArchitecture=Native32Bit
Debug|Win32|D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\|
B^D:\C++CODE\ENGINE2.0研究\ENGINE2.0\ENGINE2.0\ENGINE2.0\OPENAI\AIMAIN.CPP
B^D:\C++CODE\ENGINE2.0研究\ENGINE2.0\ENGINE2.0\ENGINE2.0\OPENAI\DEBUG\AIMAIN.OBJ
B^D:\C++CODE\ENGINE2.0研究\ENGINE2.0\ENGINE2.0\ENGINE2.0\OPENAI\DEBUG\AIMAIN.OBJ
B^D:\C++CODE\ENGINE2.0研究\ENGINE2.0\ENGINE2.0\ENGINE2.0\OPENAI\DEBUG\AIMAIN.OBJ
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{2512751B-C22A-4E16-84B8-8B94CDA63114}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>OpenAI</RootNamespace>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="aimain.cpp" />
</ItemGroup>
<ItemGroup>
<Text Include="AIDocument.txt" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="UdpClient.hpp" />
<ClInclude Include="UdpServer.hpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<Text Include="AIdoc.txt">
<Filter>头文件</Filter>
</Text>
</ItemGroup>
<ItemGroup>
<ClInclude Include="UdpServer.hpp">
<Filter>源文件</Filter>
</ClInclude>
<ClInclude Include="UdpClient.hpp">
<Filter>源文件</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="aimain.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
</Project>
\ No newline at end of file
//====客户端代码(udp_client.cpp)====//
#include <iostream> // c++std
#include <string> // c++std
#include <WinSock2.h> // win api
#pragma comment(lib, "ws2_32.lib") // link windows os static lib
bool UdpClient() {
// 初始化Winsock
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
// 创建UDP套接字
SOCKET clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (clientSocket == INVALID_SOCKET) {
std::cerr << "[client] Failed to create socket" << std::endl;
WSACleanup();
return false;
}
// 设置服务器地址
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务器IP
serverAddr.sin_port = htons(8888); // 服务器PORT
// 发送数据
// 分析:UDP通信前不需要建立连接,直接发送数据即可
std::string message = "Hello, UDP server ... ";
sendto(clientSocket, message.c_str(), message.length(), 0, (sockaddr*)&serverAddr, sizeof(serverAddr));
// 关闭套接字
closesocket(clientSocket);
WSACleanup();
return true;
}
#if 0 // linux系统实现
//=========服务端实例============
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define BUF_SIZE 1024
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
char buffer[BUF_SIZE];
// 创建socket
server_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (server_fd < 0) {
std::cerr << "Error creating socket" << std::endl;
return 1;
}
// 设置服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
// 绑定地址
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
std::cerr << "Error binding address" << std::endl;
return 1;
}
std::cout << "Server listening on port " << PORT << std::endl;
// 接收数据
socklen_t client_addr_len = sizeof(client_addr);
int recv_len = recvfrom(server_fd, buffer, BUF_SIZE, 0, (struct sockaddr*)&client_addr, &client_addr_len);
if (recv_len < 0) {
std::cerr << "Error receiving data" << std::endl;
return 1;
}
std::cout << "Received message from client: " << buffer << std::endl;
// 关闭socket
close(server_fd);
return 0;
}
//=========客户端实例=======================
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8888
#define SERVER_IP "127.0.0.1"
#define BUF_SIZE 1024
int main() {
int client_fd;
struct sockaddr_in server_addr;
char buffer[BUF_SIZE] = "Hello from client";
// 创建socket
client_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (client_fd < 0) {
std::cerr << "Error creating socket" << std::endl;
return 1;
}
// 设置服务器地址
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
// 发送数据
if (sendto(client_fd, buffer, strlen(buffer), 0, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
std::cerr << "Error sending data" << std::endl;
return 1;
}
std::cout << "Message sent to server: " << buffer << std::endl;
// 关闭socket
close(client_fd);
return 0;
}
#endif
#if 1 // windows系统实现
//====以下是一个简单的UDP通信协议服务端和客户端的实例,分别实现在不同的文件中。
//====服务端代码(udp_server.cpp):
#include <iostream>
#include <string>
#include <WinSock2.h> // win系统提供api
#pragma comment(lib, "ws2_32.lib") // 静态库
using namespace std; // 引入命名空间
bool UdpServer() {
// 初始化Winsock
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
// 创建UDP套接字
SOCKET serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (serverSocket == INVALID_SOCKET) {
std::cerr << "Failed to create socket" << std::endl;
WSACleanup();
return false;
}
// 绑定端口
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY; // 服务端IP
serverAddr.sin_port = htons(8888); // 服务端PORT
if (bind(serverSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::cerr << "Failed to bind socket" << std::endl;
closesocket(serverSocket);
WSACleanup();
return false;
}
while (true) {
// 接收数据
char buffer[1024] = { 0 };
sockaddr_in clientAddr;
int clientAddrSize = sizeof(clientAddr);
int recvSize = recvfrom(serverSocket, buffer, sizeof(buffer), 0, (sockaddr*)&clientAddr, &clientAddrSize);
if (recvSize > 0) {
buffer[recvSize] = '\0';
std::cout << "Received message from client: " << buffer << std::endl;
}
}
// 关闭套接字
closesocket(serverSocket);
WSACleanup();
return true;
}
#endif
#include "UdpServer.hpp"
#include "UdpClient.hpp"
int main() // ں
{
//UdpServer();
UdpClient();
return 0;
}
......@@ -22,6 +22,8 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "HelloHttp", "HelloHttp\Hell
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "EasyHttpClient", "EasyHttpClient\EasyHttpClient.vcxproj", "{AF5F029F-5D36-4685-B964-757AED278840}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "OpenAI", "OpenAI\OpenAI.vcxproj", "{2512751B-C22A-4E16-84B8-8B94CDA63114}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Win32 = Debug|Win32
......@@ -56,6 +58,10 @@ Global
{AF5F029F-5D36-4685-B964-757AED278840}.Debug|Win32.Build.0 = Debug|Win32
{AF5F029F-5D36-4685-B964-757AED278840}.Release|Win32.ActiveCfg = Release|Win32
{AF5F029F-5D36-4685-B964-757AED278840}.Release|Win32.Build.0 = Release|Win32
{2512751B-C22A-4E16-84B8-8B94CDA63114}.Debug|Win32.ActiveCfg = Debug|Win32
{2512751B-C22A-4E16-84B8-8B94CDA63114}.Debug|Win32.Build.0 = Debug|Win32
{2512751B-C22A-4E16-84B8-8B94CDA63114}.Release|Win32.ActiveCfg = Release|Win32
{2512751B-C22A-4E16-84B8-8B94CDA63114}.Release|Win32.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
生成启动时间为 2024/4/22 15:23:51。
1>项目“D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\EasyClient\EasyClient.vcxproj”在节点 2 上(Rebuild 个目标)。
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V120\Microsoft.CppBuild.targets(381,5): warning MSB8028: The intermediate directory (D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\\..\tmp\Debug\) contains files shared from another project (EasyHttpClient.vcxproj, EasyServer.vcxproj, Engine1.0.vcxproj, HelloCpp.vcxproj, HelloHttp.vcxproj). This can lead to incorrect clean and rebuild behavior.
1>ClCompile:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\CL.exe /c /I..\Depends\include /ZI /nologo /W3 /WX- /sdl- /Od /Oy- /D _MBCS /Gm /EHsc /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Fo"D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\\..\tmp\Debug\\" /Fd"D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\\..\tmp\Debug\vc120.pdb" /Gd /TP /analyze- /errorReport:prompt client.cpp
client.cpp
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\log.hpp(71): warning C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\time.inl(112) : 参见“localtime”的声明
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\log.hpp(72): warning C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\stdio.h(356) : 参见“sprintf”的声明
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\log.hpp(75): warning C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\stdio.h(356) : 参见“sprintf”的声明
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\log.hpp(79): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\stdio.h(211) : 参见“fopen”的声明
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\client.hpp(196): warning C4996: 'strncpy': This function or variable may be unsafe. Consider using strncpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h(195) : 参见“strncpy”的声明
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\fdset.hpp(112): warning C4800: “int”: 将值强制为布尔值“true”或“false”(性能警告)
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\easyclient\client.cpp(118): warning C4800: “int”: 将值强制为布尔值“true”或“false”(性能警告)
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\easyclient\client.cpp(230): warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h(112) : 参见“strcpy”的声明
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\easyclient\client.cpp(231): warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\string.h(112) : 参见“strcpy”的声明
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\easyclient\client.cpp(322): warning C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\stdio.h(283) : 参见“scanf”的声明
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\log.hpp(242): warning C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\stdio.h(356) : 参见“sprintf”的声明
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\log.hpp(98): 参见对正在编译的函数 模板 实例化“char *doyou::io::Log::NewFormatStr<const char*>(const char *,const char *)”的引用
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\log.hpp(92): 参见对正在编译的函数 模板 实例化“void doyou::io::Log::PError<const char*>(const char *,const char *)”的引用
1>d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\log.hpp(206): warning C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
c:\program files (x86)\microsoft visual studio 12.0\vc\include\time.inl(112) : 参见“localtime”的声明
d:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\depends\include\log.hpp(102): 参见对正在编译的函数 模板 实例化“void doyou::io::Log::EchoReal<char*>(bool,const char *,const char *,char *)”的引用
c:\program files (x86)\microsoft visual studio 12.0\vc\include\stdio.h(356) : 参见“sprintf”的声明
Link:
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\link.exe /ERRORREPORT:PROMPT /OUT:"D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\\..\bin\Debug\EasyClient.exe" /INCREMENTAL /NOLOGO kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /MANIFEST /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /manifest:embed /DEBUG /PDB:"D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\\..\bin\Debug\EasyClient.pdb" /TLBID:1 /DYNAMICBASE /NXCOMPAT /IMPLIB:"D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\\..\bin\Debug\EasyClient.lib" /MACHINE:X86 "D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\\..\tmp\Debug\client.obj"
EasyClient.vcxproj -> D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\\..\bin\Debug\EasyClient.exe
1>已完成生成项目“D:\c++code\engine2.0研究\engine2.0\engine2.0\engine2.0\EasyClient\EasyClient.vcxproj”(Rebuild 个目标)的操作。
生成成功。
已用时间 00:00:02.33
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册