boost::Beast error The WebSocket frame payload was not valid utf8

Viewed 402

An error is passed to the callback function during the async_read operation. When displaying this error, the following line is printed

boost::Beast error The WebSocket frame payload was not valid utf8

How to solve this problem? I am transferring binary data via ws, I do not need to encode it to utf8. As a last resort, how to make the message sent by the client to the server valid?

Client code where I am sending 2 serialized protobuf messages. The first message arrives, the second one crashes.

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include "OrderManagement.grpc.pb.h"
namespace beast = boost::beast;      
namespace http = beast::http;          
namespace websocket = beast::websocket; 
namespace net = boost::asio;        
using tcp = boost::asio::ip::tcp;     

    int main(int argc, char** argv)
    {
        try
        {
    
            std::string host = "127.0.0.1";
            std::string port = "8000";
            net::io_context ioc;
            tcp::resolver resolver{ioc};
            websocket::stream<tcp::socket> ws{ioc};
            auto const results = resolver.resolve(host, port);
            auto ep = net::connect(ws.next_layer(), results);
            host += ':' + port;
            ws.set_option(websocket::stream_base::decorator(
                    [](websocket::request_type& req)
                    {
                        req.set(http::field::user_agent,
                                std::string(BOOST_BEAST_VERSION_STRING) +
                                " websocket-client-coro");
                    }));
            
            ws.handshake(host, "/");
            MailTaxi::DriverIdentification identification;
            identification.set_driverid(1);
            identification.set_token("1111111111");
            MailTaxi::Coordinate coordinate;
            coordinate.set_latitude(56.211);
            coordinate.set_longitude(123.21413);
            std::string text("1");
            text[0] = 0x01;
            // Send the message
            ws.write(net::buffer(text + identification.SerializeAsString()));
    
    
            int test = 1;
            while (test) {
                std::cin >> test;
                ws.write(net::buffer(text + coordinate.SerializeAsString()));
            }
            ws.close(websocket::close_code::normal);
        }
    
        catch(std::exception const& e)
        {
            std::cerr << "Error: " << e.what() << std::endl;
            return EXIT_FAILURE;
        }
        return EXIT_SUCCESS;
    }
0 Answers
Related