Javascript Boost::asio::async\u read\u until调用处理程序 我试图在本地网络上建立两台计算机之间的连接,一个使用Boost ASIO C++ + TCP异步服务器示例的一个稍微修改的版本,另一个使用NoDEJS。 tcp_client.js: tcpServer.cpp: #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 外部字符串坐标; 使用名称空间std; 使用boost::asio::ip::tcp; std::string内联make_days_string(){ std::time\u t now=std::time(0); 返回std::ctime(&now); } 类tcp\u连接 //使用共享\u ptr并从\u启用\u共享\u //因为我们希望保持tcp_连接对象的活动状态 //只要有一个操作引用它。 :public boost::从\u启用\u共享\u { 公众: typedef boost::共享_ptr指针; 静态指针创建(boost::asio::io_服务和io_服务){ cout

Javascript Boost::asio::async\u read\u until调用处理程序 我试图在本地网络上建立两台计算机之间的连接,一个使用Boost ASIO C++ + TCP异步服务器示例的一个稍微修改的版本,另一个使用NoDEJS。 tcp_client.js: tcpServer.cpp: #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 外部字符串坐标; 使用名称空间std; 使用boost::asio::ip::tcp; std::string内联make_days_string(){ std::time\u t now=std::time(0); 返回std::ctime(&now); } 类tcp\u连接 //使用共享\u ptr并从\u启用\u共享\u //因为我们希望保持tcp_连接对象的活动状态 //只要有一个操作引用它。 :public boost::从\u启用\u共享\u { 公众: typedef boost::共享_ptr指针; 静态指针创建(boost::asio::io_服务和io_服务){ cout,javascript,c++,node.js,tcp,boost-asio,Javascript,C++,Node.js,Tcp,Boost Asio,您的tcp_connection::start方法中的无限while循环基本上会使CPU饱和。它不仅会使CPU饱和,而且也是您设计中的一个缺陷。为什么您希望在无限循环中连续附加读处理程序并向套接字发送/写入数据?您很可能希望 在收到客户端的请求后,将写入套接字 以下是我为使其像常规客户端服务器一样工作而更改的方法: void start() { start_read(); // This is going to read after every 1ms

您的
tcp_connection::start
方法中的无限while循环基本上会使CPU饱和。它不仅会使CPU饱和,而且也是您设计中的一个缺陷。为什么您希望在无限循环中连续附加读处理程序并向套接字发送/写入数据?您很可能希望
 在收到客户端的请求后,将
写入套接字

以下是我为使其像常规客户端服务器一样工作而更改的方法:

void start() {
          start_read();

          // This is going to read after every 1ms the _coordinates variable
          usleep(1000);
          m_message = _coordinates;
        }

void start_read() {
        // Start an asynchronous operation to read a newline-delimited message.
        // When read, handle_read should kick in
        boost::asio::async_read_until(
            socket_,
            input_buffer_,
            '\n',
            boost::bind(
                &tcp_connection::handle_read,
                shared_from_this(),
                boost::asio::placeholders::error
            )
        );
    }

void handle_read(const boost::system::error_code& ec) {

        std::cout << "HANDLE_READ - line 101" << "\n";
        messageFromClient_ = "";
        if (!ec) {
            // Extract the newline-delimited message from the buffer.
            std::string line;
            std::istream is(&input_buffer_);
            std::getline(is, line);

            // Empty messages are heartbeats and so ignored.
            if (!line.empty()) {
                messageFromClient_ += line;
                std::cout << "Received: " << line << "\n";
            }
            start_read();
        }
        else {
            std::cout << "Error on receive: " << ec.message() << "\n";
        }

        start_read();

        boost::asio::async_write(
                    socket_,
                    boost::asio::buffer(m_message),
                    boost::bind(
                        &tcp_connection::handle_write,
                        shared_from_this(),
                        boost::asio::placeholders::error,
                        boost::asio::placeholders::bytes_transferred
                    )
                );
    }
void start(){
开始读取();
//每1ms读取一次_坐标变量
usleep(1000);
m_消息=_坐标;
}
无效开始读取(){
//启动异步操作以读取换行分隔的消息。
//读取时,句柄_read应启动
boost::asio::异步读取(
插座,
输入缓冲区,
“\n”,
boost::bind(
&tcp_连接::句柄_读取,
从_this()共享了_,
boost::asio::占位符::错误
)
);
}
无效句柄读取(const boost::system::error\u code&ec){

std::非常感谢您的帮助。事实上,我的CPU已经饱和。事实上,写/读部分是分开的:-服务器应该每毫秒在套接字中写入
\u坐标的内容
-客户端应该能够在需要时发送消息:目前它只是一个“收到的数据”消息,但稍后当使用HMI上链接到JS部件的按钮时,将使用一些JSON字符串来启动我程序的特定功能(在服务器端)。那么,我应该在哪里实现(更新坐标+在套接字上写入)必须每毫秒执行一次的循环?是的,您可以使用
截止时间\u计时器
每x毫秒写入一次。稍后,如果您发现它没有按照您的要求进行缩放(或者您的读取处理程序开始变得更昂贵或阻塞)然后,你可以考虑使用多个线程来写和读,非常感谢你,@ Arunmu!我用<代码> DealLythTime<代码>来写,并且它的工作如预期的(考虑到我不需要精确性)。
#include <ctime>
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>

extern string _coordinates;

using namespace std;
using boost::asio::ip::tcp;

std::string inline make_daytime_string() {
    std:: time_t now = std::time(0);
    return std::ctime(&now);
}

class tcp_connection
    // Using shared_ptr and enable_shared_from_this
    // because we want to keep the tcp_connection object alive
    // as long as there is an operation that refers to it.
    : public boost::enable_shared_from_this<tcp_connection>
    {
    public:
        typedef boost::shared_ptr<tcp_connection> pointer;

        static pointer create(boost::asio::io_service& io_service) {
            cout << "Creates a pointer for the tcp connection" <<endl;
            return pointer(new tcp_connection(io_service));
        }

        tcp::socket& socket() {
            return socket_;
        }

        // Call boost::asio::async_write() to serve the data to the client.
        // We are using boost::asio::async_write(),
        // rather than ip::tcp::socket::async_write_some(),
        // to ensure that the entire block of data is sent.

        void start() {
            while(1) {
                start_read();

                // This is going to read after every 1ms the _coordinates variable
                usleep(1000);

                m_message = _coordinates;

                boost::asio::async_write(
                    socket_,
                    boost::asio::buffer(m_message),
                    boost::bind(
                        &tcp_connection::handle_write,
                        shared_from_this(),
                        boost::asio::placeholders::error,
                        boost::asio::placeholders::bytes_transferred
                    )
                );
            }
        }

private:
    tcp_connection(boost::asio::io_service& io_service)
        : socket_(io_service)
        {
        }

    void start_read() {
        // Start an asynchronous operation to read a newline-delimited message.
        // When read, handle_read should kick in
        boost::asio::async_read_until(
            socket_,
            input_buffer_,
            '\n',
            boost::bind(
                &tcp_connection::handle_read,
                shared_from_this(),
                boost::asio::placeholders::error
            )
        );
    }

    // When stream is received, handle the message from the client
    void handle_read(const boost::system::error_code& ec) {

        std::cout << "HANDLE_READ - line 101" << "\n";
        messageFromClient_ = "";
        if (!ec) {
            // Extract the newline-delimited message from the buffer.
            std::string line;
            std::istream is(&input_buffer_);
            std::getline(is, line);

            // Empty messages are heartbeats and so ignored.
            if (!line.empty()) {
                messageFromClient_ += line;
                std::cout << "Received: " << line << "\n";
            }
            start_read();
        }
        else {
            std::cout << "Error on receive: " << ec.message() << "\n";
        }
    }

    // handle_write() is responsible for any further actions
    // for this client connection.
    void handle_write(const boost::system::error_code& /*error*/, size_t /*bytes_transferred*/) {
        m_message += "helloo\n";
    }

    tcp::socket socket_;
    std::string m_message;
    boost::asio::streambuf input_buffer_;
    std::string messageFromClient_;
};

class tcp_server {
    public:
        // Constructor: initialises an acceptor to listen on TCP port 14002.
        tcp_server(boost::asio::io_service& io_service)
        : acceptor_(io_service, tcp::endpoint(tcp::v4(), 14002))
        {
            // start_accept() creates a socket and
            // initiates an asynchronous accept operation
            // to wait for a new connection.
            start_accept();
        }

private:
    void start_accept() {
        // creates a socket
        cout << "creating a new socket for the communication" <<endl;
        tcp_connection::pointer new_connection = tcp_connection::create(acceptor_.get_io_service());

        // initiates an asynchronous accept operation
        // to wait for a new connection.
        acceptor_.async_accept(
            new_connection->socket(),
            boost::bind(
                &tcp_server::handle_accept,
                this,
                new_connection,
                boost::asio::placeholders::error
            )
        );
    }

    // handle_accept() is called when the asynchronous accept operation
    // initiated by start_accept() finishes. It services the client request
    void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code& error) {

        if (!error) {
            cout << "Starting the new tcp connection" <<endl;
            new_connection->start();
        }

        // Call start_accept() to initiate the next accept operation.
        start_accept();
    }

    tcp::acceptor acceptor_;
};


int inline launch_server() {
    try {
        boost::asio::io_service io_service;
        tcp_server server(io_service);

        // Run the io_service object to perform asynchronous operations.
        io_service.run();
    }
    catch (std::exception& e) {
        std::cerr << e.what() << std::endl;
    }
    return 0;
}
void start() {
          start_read();

          // This is going to read after every 1ms the _coordinates variable
          usleep(1000);
          m_message = _coordinates;
        }

void start_read() {
        // Start an asynchronous operation to read a newline-delimited message.
        // When read, handle_read should kick in
        boost::asio::async_read_until(
            socket_,
            input_buffer_,
            '\n',
            boost::bind(
                &tcp_connection::handle_read,
                shared_from_this(),
                boost::asio::placeholders::error
            )
        );
    }

void handle_read(const boost::system::error_code& ec) {

        std::cout << "HANDLE_READ - line 101" << "\n";
        messageFromClient_ = "";
        if (!ec) {
            // Extract the newline-delimited message from the buffer.
            std::string line;
            std::istream is(&input_buffer_);
            std::getline(is, line);

            // Empty messages are heartbeats and so ignored.
            if (!line.empty()) {
                messageFromClient_ += line;
                std::cout << "Received: " << line << "\n";
            }
            start_read();
        }
        else {
            std::cout << "Error on receive: " << ec.message() << "\n";
        }

        start_read();

        boost::asio::async_write(
                    socket_,
                    boost::asio::buffer(m_message),
                    boost::bind(
                        &tcp_connection::handle_write,
                        shared_from_this(),
                        boost::asio::placeholders::error,
                        boost::asio::placeholders::bytes_transferred
                    )
                );
    }