Boost.Asio即时数据传输至服务器

问题描述 投票:0回答:1

我遇到一个问题,除非套接字或发送关闭并且循环再次迭代以在套接字上传输更多数据,否则数据不会立即传输到服务器。 我用另一个java程序测试了服务器,以确保它在它的一侧正常工作

这是代码:

#include <boost/asio.hpp>
#include <iostream>
#include "Thread.h"
using namespace std;
using namespace boost;
const char* o = new char(1);
class Stream
{
    
public:
    Stream(string IP, int port) {
        bool conncected = false;
        boost::system::error_code ec;
        boost::asio::io_context io_context;
        boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(IP), port);
        boost::asio::ip::tcp::socket socket(io_context);

        
        try {
            socket.connect(endpoint);
            conncected = true;

        }
        catch (const boost::system::system_error& e) {
            std::cout << "Error: " << e.what() << std::endl;
            conncected = false;
        }
        
        if (conncected)
        {
            Thread* mainStream = new Thread([this, &socket, &io_context,&endpoint]() {
                std::vector<boost::asio::const_buffer> buffers;
              
                while (true)
                {
                   
                    cout << "enter a message\n";
                    string message;
                    std::getline(std::cin, message);
                    message += '\n';
                    buffers.push_back(boost::asio::buffer(message.data(), message.size()));
                    auto begin = boost::asio::buffers_begin(buffers);
                    auto end = boost::asio::buffers_end(buffers);

                        boost::asio::async_write(socket, buffers,
                        [this, &buffers, &socket, &io_context, &endpoint](const boost::system::error_code& error, std::size_t bytes_transferred) {
                                if (!error) {

                                    std::cout << "Sent " << bytes_transferred << " bytes to the server" << std::endl;
                                    
                                    //error data is delayed untily client is closed despite this code slot being called
                                    /*trigger an immediate transmission of data here like
                                    socket.shutdown(socket.shutdown_send);
                                    socket.close();
                                    but with the stream being opened for more write
                                    operations in the loop
                                    */
                                }
                                else {
                                    std::cout << "Error sending message: " << error.message() << std::endl;
                                    std::cout << "reconnecting to the server " << std::endl;
                                    bool timeout = false;
                                    new Thread([&timeout]() {Sleep(3000); timeout = true; });
                                    while (true)
                                    {
                                        try {

                                            socket.connect(endpoint);
                                            break;

                                        }
                                        catch (const boost::system::system_error& e) {

                                            if (timeout)
                                            {
                                                std::cout << "couldn't connect to server" << std::endl;
                                                break;
                                            }
                                        }
                                    }
                                }
                            });
                    io_context.run();
                    io_context.restart();
                   
                }
                });
            mainStream->join();
        }
        else
        {
            cout << "please check that connection requirements are met" << endl;
        }
           


    }
};

int main() {
    new Stream("127.0.0.1", 8080);
    return 0;
}

尝试过: 发送 异步发送 写一些 写

想要: 不断向服务器传输数据而不关闭套接字或流

boost-asio
1个回答
0
投票

代码有很多奇怪之处

  • 不必要的使用
    new
    导致内存泄漏
  • 线程 t{f}; t.join();只是一种非常昂贵的 f() 方法
  • 在缓冲区序列中不必要地包装缓冲区
  • 缓冲区中不必要的消息大小指定
  • 通过阻止服务运行和重启来取消异步操作
  • 相同不必要的序列上未使用的缓冲区迭代器

在我看来你想写的可以写成

#include <boost/asio.hpp>
#include <iostream>
namespace asio = boost::asio;

void Stream(std::string IP, uint16_t port) {
    using asio::ip::tcp;
    using boost::system::error_code;

    for (asio::system_executor ex;;) {
        tcp::socket socket(ex);
        connect(socket, tcp::resolver{ex}.resolve(IP, std::to_string(port)));

        for (std::string message; std::cout << "enter a message: ", getline(std::cin, message);) {
            message += '\n';

            error_code ec;
            size_t     n = write(socket, asio::buffer(message), ec);
            std::cout << "Sent " << n << " bytes (" << ec.message() << ")" << std::endl;
            if (ec.failed())
                continue; // new connection

        }
    }
}

int main() { //
    Stream("127.0.0.1", 8080);
}
© www.soinside.com 2019 - 2024. All rights reserved.