netcpp
0.5.0
[한국어]
netcpp 是简单的C++ 网络库。它支持windows和linux平台。
该库支持 vcpkg 端口。如果您已经安装了 vcpkg,则只需使用下面的命令行即可安装此软件包。
vcpkg install netcpp # In classic mode
vcpkg add port netcpp # In manifest mode
或者克隆此存储库,然后执行下面的命令行。
git clone https://github.com/index1207/netcpp.git && cd netcpp # clone and move directory
cmake -B build # CMake Configuration
cmake --build build --config < BUILD_MODE > # Build library
cmake --install build --config < BUILD_MODE > --prefix < PATH_TO_INSTALL > # Install to other project
netcpp 提供 CMake 目标:
find_package (netcpp CONFIG REQUIRED)
target_link_libraries (main PRIVATE netcpp::netcpp)
选项 | 描述 |
---|---|
NETCPP_BUILD_SHARED | 通过共享库构建 |
NETCPP_TEST | 在构建中包含单元测试 |
// <net/socket.hpp>
net::socket tcp_socket (net::protocol::tcp); // Create a TCP socket
net::socket udp_socket (net::protocol::udp); // Create a UDP socket
net::socket empty_socket;
empty_socket.create(net::protocol::tcp); // Create a new TCP socket
// <net/context.hpp>
net::socket sock (net::protocol::tcp); // Create a new TCP socket.
net::context connect_ctx; // A context that necessary to async I/O
connect_ctx.endpoint = ENDPOINT; // Specify the endpoint.
connect_ctx.completed = [](net::context* ctx, bool success) { // callback
if (success)
{
std::cout << " Connected " << std::endl;
}
else
{
std::cout << " Failed to connect " << std::endl;
}
};
sock.connect(&connect_ctx); // Connect to specified endpoint asynchronously.
// Server
# include < net/Socket.hpp >
# include < iostream >
int main ()
{
net::native::initialize (); // Initialize Native API
net::socket sock (net::protocol::tcp); // Create new TCP socket
if (!sock. is_open ()) // Validate socket
return - 1 ;
if (!sock. bind ( net::endpoint (net::ip_address::loopback, 8085 ))) // Bind the address `tcp://loopback:8085`
return - 1 ;
if (!sock. listen ()) // Ready to accept
return - 1 ;
while ( true )
{
auto client = sock. accept (); // accept other client. it returns new client socket.
std::cout << " Connected n " ;
}
}
// Client
# include < net/socket.hpp >
# include < iostream >
int main ()
{
net::native::initialize (); // Initialize Native API
net::socket sock (net::protocol::tcp); // Create new TCP socket
if (!sock. is_open ()) // Validate socket
return - 1 ;
if (!sock. connect ( net::endpoint (net::ip_address::loopback, 8085 ))) // Try to connect to server.
return - 1 ;
std::cout << " Connected! " ;
}
// <net/dns.hpp>
net::dns::get_host_name () // get host's name
net::dns::get_host_entry( " www.example.com " ) // get www.example.com's host entry
try {
if (!sock. connect (ENDPOINT))
throw net::network_exception ( " connect() " );
}
catch (std:: exception & e) {
std::cout << e. what () << std::endl; // connect(): Cannot assign requested address. [10049]
}
操作系统 | 图书馆 |
---|---|
视窗 | 温索克2 |
Linux | 利布林 |
该存储库随时欢迎任何问题或 PR!