📅  最后修改于: 2023-12-03 15:14:17.193000             🧑  作者: Mango
CromA是一款基于C++11标准的轻量级跨平台网络库,支持TCP/IP协议和UDP协议。它的设计理念是尽可能地提供简单易用的API,同时保证高效和可扩展性。
CromA使用CMake进行构建,可以在Windows,Linux和macOS上构建。首先克隆CromA到本地:
git clone https://github.com/huxiaotian02/CromA.git
然后使用CMake构建项目:
mkdir build && cd build
cmake ..
make
如果你使用的是Windows平台,可以在生成的Visual Studio解决方案中进行构建。
#include "CromA/TcpServer.h"
#include "CromA/Log.h"
void OnConnection(const CromA::TcpConnectionPtr& conn)
{
LOG_INFO("New connection from {}.", conn->GetPeerAddress().ToString());
conn->Send("Welcome to CromA server.\n");
}
void OnMessage(const CromA::TcpConnectionPtr& conn, CromA::Buffer& buffer)
{
std::string message = buffer.ReadAllAsString();
LOG_INFO("Received {} bytes from {} : {}", message.size(), conn->GetPeerAddress().ToString(), message);
conn->Send(message);
}
int main()
{
CromA::TcpServer server;
server.SetConnectionCallback(OnConnection);
server.SetMessageCallback(OnMessage);
server.Start("0.0.0.0", 8888);
return 0;
}
#include "CromA/TcpClient.h"
#include "CromA/Log.h"
void OnConnection(const CromA::TcpConnectionPtr& conn)
{
LOG_INFO("Connected to {}.", conn->GetPeerAddress().ToString());
conn->Send("Hello, CromA server.\n");
}
void OnMessage(const CromA::TcpConnectionPtr& conn, CromA::Buffer& buffer)
{
std::string message = buffer.ReadAllAsString();
LOG_INFO("Received {} bytes from {} : {}", message.size(), conn->GetPeerAddress().ToString(), message);
}
int main()
{
CromA::TcpClient client;
client.SetConnectionCallback(OnConnection);
client.SetMessageCallback(OnMessage);
client.Connect("127.0.0.1", 8888);
return 0;
}
#include "CromA/UdpSocket.h"
#include "CromA/Log.h"
void OnMessage(const CromA::UdpEndpoint& endpoint, CromA::Buffer& buffer)
{
std::string message = buffer.ReadAllAsString();
LOG_INFO("Received {} bytes from {} : {}", message.size(), endpoint.ToString(), message);
// 回复消息给客户端
CromA::UdpSocket::GetInstance().SendTo(message, endpoint);
}
int main()
{
CromA::UdpSocket::GetInstance().SetMessageCallback(OnMessage);
CromA::UdpSocket::GetInstance().Bind("0.0.0.0", 8888);
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
#include "CromA/UdpSocket.h"
#include "CromA/Log.h"
void OnMessage(const CromA::UdpEndpoint& endpoint, CromA::Buffer& buffer)
{
std::string message = buffer.ReadAllAsString();
LOG_INFO("Received {} bytes from {} : {}", message.size(), endpoint.ToString(), message);
}
int main()
{
CromA::UdpEndpoint serverEndpoint("127.0.0.1", 8888);
CromA::UdpSocket::GetInstance().SetMessageCallback(OnMessage);
CromA::UdpSocket::GetInstance().SendTo("Hello, CromA server.", serverEndpoint);
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
更多示例可以在源代码中的examples目录下找到。