Заголовок только C++ сетевой библиотеки, основанный на asio, поддерживает TCP, UDP, HTTP, WebSocket, RPC, SSL, ICMP, serial_port.
Примерный каталог содержит большое количество примеров кода и разнообразные методы использования, обратитесь к примеру кода.
asio2::tcp_server server;
server.bind_recv([&server](std::shared_ptr<asio2::tcp_session> & session_ptr, std::string_view s) {
session_ptr->no_delay(true);
printf("recv : %zu %.*s\n", s.size(), (int)s.size(), s.data());
session_ptr->async_send(s);
}).bind_connect([&server](auto & session_ptr) {
printf("client enter : %s %u %s %u\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
session_ptr->local_address().c_str(), session_ptr->local_port());
}).bind_disconnect([&server](auto & session_ptr) {
printf("client leave : %s %u %s\n",
session_ptr->remote_address().c_str(), session_ptr->remote_port(),
asio2::last_error_msg().c_str());
});
server.start("0.0.0.0", 8080);
// Автоматическая распаковка по \n (можно указать произвольные символы)
//server.start("0.0.0.0", 8080, '\n');
// Автоматическая распаковка по \r\n (можно задать произвольную строку)
//server.start("0.0.0.0", 8080, "\r\n");
// Автоматическая распаковка в соответствии с правилами, указанными match_role
// (см. демонстрационный код для match_role) (для распаковки пользовательского протокола)
//server.start("0.0.0.0", 8080, match_role('#'));
// Получать фиксированные 100 байт за раз
//server.start("0.0.0.0", 8080, asio::transfer_exactly(100));
// TCP в режиме датаграмм, независимо от того, как долго данные отправляются, весь пакет данных соответствующей длины должен быть получен обеими сторонами.
//server.start("0.0.0.0", 8080, asio2::use_dgram);
asio2::tcp_client client;
// Клиент автоматически переподключится при отключении
// [опция повторного подключения по умолчанию включена]
// отключить автоматическое повторное подключение
//client.auto_reconnect(false);
// включить автоматическое повторное подключение и использовать задержку по умолчанию
//client.auto_reconnect(true);
// включить автоматическое повторное подключение и использовать настраиваемую задержку
client.auto_reconnect(true, std::chrono::seconds(3));
client.bind_connect([&]() {
if (asio2::get_last_error())
printf("connect failure : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
else
printf("connect success : %s %u\n", client.local_address().c_str(), client.local_port());
client.async_send("<abcdefghijklmnopqrstovuxyz0123456789>");
}).bind_disconnect([]() {
printf("disconnect : %d %s\n", asio2::last_error_val(), asio2::last_error_msg().c_str());
}).bind_recv([&](std::string_view sv) {
printf("recv : %zu %.*s\n", sv.size(), (int)sv.size(), sv.data());
client.async_send(sv);
})
//// Привязка глобальных функций
//.bind_recv(on_recv)
//// Привязка функций-членов (подробности см. в демонстрационном коде)
//.bind_recv(std::bind(&listener::on_recv, &lis, std::placeholders::_1))
//// Связывание функций-членов по ссылке на объект lis (подробности см. в демонстрационном коде)
//.bind_recv(&listener::on_recv, lis)
//// Связать функции-члены через указатели на объект lis (подробности см. в демонстрационном коде)
//.bind_recv(&listener::on_recv, &lis)
;
// Асинхронное подключение к серверу
client.async_start("0.0.0.0", 8080);
// Синхронное подключение к серверу
//client.start("0.0.0.0", 8080);
//client.async_start("0.0.0.0", 8080, '\n');
//client.async_start("0.0.0.0", 8080, "\r\n");
//client.async_start("0.0.0.0", 8080, match_role);
//client.async_start("0.0.0.0", 8080, asio::transfer_exactly(100));
//client.start("0.0.0.0", 8080, asio2::use_dgram);
## UDP:
##### Сервер:
```c++
...
``` **Перевод текста на русский язык:**
asio2::udp_server server; // ... Binding listener (see demo code) server.start("0.0.0.0", 8080); // general UDP //server.start("0.0.0.0", 8080, asio2::use_kcp); // Reliable UDP
##### client:
```c++
asio2::udp_client client;
// ... Binding listener (see demo code)
client.start("0.0.0.0", 8080);
//client.async_start("0.0.0.0", 8080, asio2::use_kcp); // Reliable UDP
// If you want to know which client called this function, set the first parameter
// to std::shared_ptr<asio2::rpc_session>& session_ptr, If you don't want to,keep
// it empty is ok.
int add(std::shared_ptr<asio2::rpc_session>& session_ptr, int a, int b)
{
return a + b;
}
// Specify the "max recv buffer size" to avoid malicious packets, if some client
// sent data packets size is too long to the "max recv buffer size", then the
// client will be disconnect automatic .
asio2::rpc_server server(
512, // the initialize recv buffer size :
1024, // the max recv buffer size :
4 // the thread count :
);
// ... Binding listener (see demo code)
A a; // For the definition of A, see the demo code
// Binding RPC global functions
server.bind("add", add);
// Binding RPC member functions
server.bind("mul", &A::mul, a);
// Binding lambda
server.bind("cat", [&](const std::string& a, const std::string& b) { return a + b; });
// Binding member functions (by reference)
server.bind("get_user", &A::get_user, a);
// Binding member functions (by pointer)
server.bind("del_user", &A::del_user, &a);
server.start("0.0.0.0", 8080);
asio2::rpc_client client;
// ... Binding listener (see demo code)
client.start("0.0.0.0", 8080);
// Synchronized invoke RPC functions
int sum = client.call<int>(std::chrono::seconds(3), "add", 11, 2);
printf("sum : %d err : %d %s\n", sum, asio2::last_error_val(), asio2::last_error_msg().c_str());
// Asynchronous invocation of RPC function, the first parameter is the callback function,
// when the call is completed or timeout, the callback function automatically called.
client.async_call([](int v)
{
// if timeout or other errors, you can get the error info by asio2::get_last_error.
printf("sum : %d err : %d %s\n", v, asio2::last_error_val(), asio2::last_error_msg().c_str());
}, "add", 10, 20);
// Result value is user-defined data type (see demo code for the definition of user type)
user u = client.call<user>("get_user");
printf("%s %d ", u.name.c_str(), u.age);
for (auto &[k, v] : u.purview)
{
printf("%d %s ", k, v.c_str());
}
printf("\n");
u.name = "hanmeimei";
u.age = ((int)time(nullptr)) % 100;
u.purview = { {10,"get"},{20,"set"} };
// If the result value of the RPC function is void, then the user callback
// function has only one parameter.
client.async_call([]()
{
}, "del_user", std::move(u));
// just call rpc function, don't need result
client.async_call("del_user", std::move(u));
struct aop_log
{
bool before(http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(rep);
printf("aop_log before %s\n", req.method_string().data());
return true;
}
bool after(std::shared_ptr<asio2::http_session>& session_ptr,
http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(session_ptr, req, rep);
printf("aop_log after\n");
return true;
}
};
struct aop_check
{
bool before(std::shared_ptr<asio2::http_session>& session_ptr,
http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(session_ptr, req, rep);
printf("aop_check before\n");
return true;
}
bool after(http::web_request& req, http::web_response& rep)
{
asio2::detail::ignore_unused(req, rep);
printf("aop_check after\n");
return true;
}
};
asio2::http_server server;
server.bind_recv([&](http::web_request& req, http::web_response& rep)
{
std::cout << req.path() << std::endl;
std::cout << req.query() << std::endl;
``` **Параметры порта здесь**
sp.socket().set_option(asio::serial_port::flow_control(asio::serial_port::flow_control::type::none));
sp.socket().set_option(asio::serial_port::parity(asio::serial_port::parity::type::none));
sp.socket().set_option(asio::serial_port::stop_bits(asio::serial_port::stop_bits::type::one));
sp.socket().set_option(asio::serial_port::character_size(8));
}).bind_recv([&](std::string_view sv)
{
printf("recv : %zu %.*s\n", sv.size(), (int)sv.size(), sv.data());
std::string s;
uint8_t len = uint8_t(10 + (std::rand() % 20));
s += '<';
for (uint8_t i = 0; i < len; i++)
{
s += (char)((std::rand() % 26) + 'a');
}
s += '>';
sp.async_send(std::move(s));
});
//sp.start(device, baud_rate);
sp.start(device, baud_rate, '>');
//sp.start(device, baud_rate, "\r\n");
//sp.start(device, baud_rate, match_role);
//sp.start(device, baud_rate, asio::transfer_at_least(1));
//sp.start(device, baud_rate, asio::transfer_exactly(10));
asio2::timer timer;
timer.start_timer(1, std::chrono::seconds(1), [&]()
{
printf("timer 1\n");
if (true)
timer.stop_timer(1);
});
timer.start_timer("id2", 2000, 5, []()
{
printf("timer id2, loop 5 times\n");
});
timer.start_timer(5, std::chrono::milliseconds(1000), std::chrono::milliseconds(5000), []()
{
printf("timer 5, loop infinite, delay 5 seconds\n");
});
asio2::tcp_client client;
// Post an asynchronous condition event that is never executed unless it is manually triggered
std::shared_ptr<asio2::condition_event> event_ptr = client.post_condition_event([]()
{
// do something.
});
client.bind_recv([&](std::string_view data)
{
// For example, to achieve a certain condition
if (data == "some_condition")
{
// Trigger the event to start execution
event_ptr->notify();
}
});
Вы можете оставить комментарий после Вход в систему
Неприемлемый контент может быть отображен здесь и не будет показан на странице. Вы можете проверить и изменить его с помощью соответствующей функции редактирования.
Если вы подтверждаете, что содержание не содержит непристойной лексики/перенаправления на рекламу/насилия/вульгарной порнографии/нарушений/пиратства/ложного/незначительного или незаконного контента, связанного с национальными законами и предписаниями, вы можете нажать «Отправить» для подачи апелляции, и мы обработаем ее как можно скорее.
Комментарии ( 0 )