如何将 boost asio tcp 套接字传递给线程以将心跳发送到客户端或服务器

How to pass a boost asio tcp socket to a thread for sending heartbeat to client or server(如何将 boost asio tcp 套接字传递给线程以将心跳发送到客户端或服务器)
本文介绍了如何将 boost asio tcp 套接字传递给线程以将心跳发送到客户端或服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在用 boost TCP 编写一个客户端/服务器程序,其中我想每 2 秒向客户端发送一次 HEARTBEAT 消息,我正在尝试创建一个新线程,通过它我可以轻松地发送它但无法解决它.我正在使用 boost::thread t(hearbeatSender,sock); 创建线程.但给出了很多错误.我也使用 bind 将函数名与套接字绑定,但没有解决错误.

I am writing a client/server program in boost TCP in which I want to send a HEARTBEAT message to the client every 2 seconds for which I am trying to create a new thread by which I can send it easily but unable to solve it. I am creating thread using boost::thread t(hearbeatSender,sock); this. but giving lots of errors. I also use bind to bind function name with the socket but not resolved the error.

void process(boost::asio::ip::tcp::socket & sock);
std::string read_data(boost::asio::ip::tcp::socket & sock);
void write_data(boost::asio::ip::tcp::socket & sock,std::string);
void hearbeatSender(boost::asio::ip::tcp::socket & sock);
int main()
{

    unsigned short port_num = 3333;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address_v4::any(), port_num);
    boost::asio::io_service io;
    try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);
        boost::thread t(hearbeatSender,sock); 
        process(sock);
        t.join();

    }
    catch (boost::system::system_error &e)
    {
        std::cout << "Error occured! Error code = " << e.code()
        << ". Message: " << e.what();

        return e.code().value();
    }
  return 0;

}
void process(boost::asio::ip::tcp::socket & sock)
{
    while(1){
    std::string data = read_data(sock);
    std::cout<<"Client's request is: "<<data<<std::endl;
    write_data(sock,data);
    }
}
std::string read_data(boost::asio::ip::tcp::socket & sock)
{
    boost::asio::streambuf buf;
    boost::asio::read_until(sock, buf, "
");
    std::string data = boost::asio::buffer_cast<const char*>(buf.data());
    return data;
}
void write_data(boost::asio::ip::tcp::socket & sock,std::string data)
{
    boost::system::error_code error;
    std::string msg;
    int ch = data[0]-'0';
    switch(ch)
    {
        case 1: msg = "Case 1
"; break;
        case 2: msg = "Case 2
"; break;
        case 3: msg = "Case 3
"; break;
        case 4: msg = "Case 4
"; break;
        default: msg  = "Case default
"; break;
    }
    boost::asio::write( sock, boost::asio::buffer(msg+ "
"), error );
     if( !error ) {
        std::cout << "Server sent hello message!" << std::endl;
     }
     else {
        std::cout << "send failed: " << error.message() << std::endl;
     }
}
void hearbeatSender(boost::asio::ip::tcp::socket & sock)
{
    boost::system::error_code error;
    std::string msg = "HEARTBEAT";
    while(1)
    {
        sleep(2);
        std::cout<<msg<<std::endl;
        boost::asio::write( sock, boost::asio::buffer(msg+ "
"), error );
        if( !error ) {
        std::cout << "Server sent HEARTBEAT message!" << std::endl;
        }
        else {
            std::cout << "send failed: " << error.message() << std::endl;
        }
    }
}

这是一个服务端代码,用于响应客户端的消息并向客户端发送心跳.这是一个同步 TCP 服务器.

This is a server-side code for responding to the message of the client and sending heartbeat to the client. This is a synchronous TCP server.

推荐答案

代替这个:

try
    {
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        auto sock = acceptor.accept();
        std::thread t([&sock]() {
            hearbeatSender(sock);
        });
        process(sock);
        t.join();

    }

使用它:

try{
        boost::asio::ip::tcp::acceptor acceptor(io, ep.protocol());
        acceptor.bind(ep);
        acceptor.listen();
        boost::asio::ip::tcp::socket sock(io);
        acceptor.accept(sock);

        std::thread t([&sock]() {
            hearbeatSender(sock);
        });
        process(sock);
        t.join();
}

还包括头文件:

#include <thread>
#include <chrono>

(可选)你也可以使用 this_thread::sleep_for 而不是 sleep()std::this_thread::sleep_for(std::chrono::seconds(10));

(Optional) you can also use this_thread::sleep_for instead of sleep() std::this_thread::sleep_for(std::chrono::seconds(10));

把socket传递给线程的问题解决了.

The problem of passing a socket to the thread is solved.

现在,用于在客户端和服务器之间进行 HEARTBEAT 对话.可以从这里检查完整的代码:

Now, for conversing a HEARTBEAT between a client and a server. Complete code can be checked from here:

客户端代码 HEARTBEAT 每 5 次传输秒

服务器代码,用于响应客户

这篇关于如何将 boost asio tcp 套接字传递给线程以将心跳发送到客户端或服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)