Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6627457
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T22:00:58+00:00 2026-05-25T22:00:58+00:00

Using g++ and boost::asio, I’m trying to format network message frames containing the size

  • 0

Using g++ and boost::asio, I’m trying to format network message frames containing the size of the data to be transmited:

+----------------+------------------------+
|  Length        |  Message string        |
|        4 bytes |                n bytes |
+----------------+------------------------+

Using the examples of asio blocking tcp echo client/server under a 32 byte Linux, I’m stucked with transmitting the correct size in the frame. The client is supposed to be a Windows machine.

CLIENT:

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <stdint.h>
#include <arpa/inet.h>

using boost::asio::ip::tcp;

enum { max_length = 1024 };

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 3)
    {
      std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
    tcp::resolver::iterator iterator = resolver.resolve(query);

    tcp::socket s(io_service);
    s.connect(*iterator);

    std::cout << "sizeof uint32_t=" << sizeof(uint32_t) << std::endl;

    uint32_t len = 1234;
    std::cout << "len=" << len << std::endl;

    // uint => char 4
    char char_len[4];
    char_len[0] = (len >> 0);
    char_len[1] = (len >> 8);
    char_len[2] = (len >> 16);
    char_len[3] = (len >> 24);

    std::cout << "char[4] len=[" 
        << char_len[0] << ',' << char_len[1] << ',' 
        << char_len[2] << ',' << char_len[3] << ']' 
        << std::endl;

    // char 4 => uint
    uint32_t uint_len = *(reinterpret_cast<uint32_t *>( char_len ));
    std::cout << "uint len=" << uint_len << std::endl;

    // network bytes order
    uint32_t net_len = htonl( len );
    std::cout << "net_len=" << net_len << std::endl;

    // uint => char 4
    char net_char_len[4];
    net_char_len[0] = (net_len >> 0);
    net_char_len[1] = (net_len >> 8);
    net_char_len[2] = (net_len >> 16);
    net_char_len[3] = (net_len >> 24);

    std::cout << "net char[4] len=[" 
        << net_char_len[0] << ',' << net_char_len[1] << ',' 
        << net_char_len[2] << ',' << net_char_len[3] << ']' 
        << std::endl;

    boost::asio::write(s, boost::asio::buffer(char_len, 4));

    char reply[max_length];
    size_t reply_length = boost::asio::read(s,
        boost::asio::buffer(reply, 1 ));
    std::cout << "Reply is: ";
    std::cout.write(reply, reply_length);
    std::cout << "\n";
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

SERVER:

#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>

using boost::asio::ip::tcp;

const int max_length = 1024;

typedef boost::shared_ptr<tcp::socket> socket_ptr;

void session(socket_ptr sock)
{
  try
  {
    for (;;)
    {
      char data[max_length];

      boost::system::error_code error;
      size_t length = sock->read_some(boost::asio::buffer(data), error);
      if (error == boost::asio::error::eof)
        break; // Connection closed cleanly by peer.
      else if (error)
        throw boost::system::system_error(error); // Some other error.

      uint32_t net_len;
      size_t len_len = sock->read_some( boost::asio::buffer( reinterpret_cast<char*>(&net_len), 4), error );
      std::clog << "net len=" << net_len << std::endl;
      uint32_t len = ntohl( net_len );
      std::clog << "uint len=" << len << std::endl;

      char char_len = (char)len;
      std::clog << "char len=" << len << std::endl;

      boost::asio::write(*sock, boost::asio::buffer( &char_len, size_t(1)));
    }
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception in thread: " << e.what() << "\n";
  }
}

void server(boost::asio::io_service& io_service, short port)
{
  tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
  for (;;)
  {
    socket_ptr sock(new tcp::socket(io_service));
    a.accept(*sock);
    boost::thread t(boost::bind(session, sock));
  }
}

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    std::cout << "Started" << std::endl;
    std::cout << "sizeof uint32_t=" << sizeof(uint32_t) << std::endl;
    using namespace std; // For atoi.
    server(io_service, atoi(argv[1]));
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

Should compile with a simple script:

g++ -o client -I/usr/include/boost -L/usr/lib -lboost_system -lboost_thread-mt  client.cpp
g++ -o server -I/usr/include/boost -L/usr/lib -lboost_system -lboost_thread-mt  server.cpp

The client is unable to decode the length and the server does not seems to receive the right irt. What am I missing?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T22:00:59+00:00Added an answer on May 25, 2026 at 10:00 pm

    I finally manage to find what went wrong.

    There was a residual read at the bottom of the server code, that was preventing the second one to read the correct bytes, as said @PRouleau.

    The client was also writing the wrong variable, as @Nim pointed out.

    The sevrer’s error check was not at the right place.

    Finally I get the following outpout:

    Client:

    sizeof uint32_t=4
    len=1234
    uint len=1234
    net_len=3523477504
    net char[4] len=[0,0,4,-46]
    

    Server:

    Started
    sizeof uint32_t=4
    net len=3523477504
    uint len=1234
    

    With the following code :

    CLIENT:

    #include <cstdlib>
    #include <cstring>
    #include <iostream>
    #include <boost/asio.hpp>
    #include <stdint.h>
    #include <arpa/inet.h>
    
    using boost::asio::ip::tcp;
    
    enum { max_length = 1024 };
    
    int main(int argc, char* argv[])
    {
      try
      {
        if (argc != 3)
        {
          std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
          return 1;
        }
    
        boost::asio::io_service io_service;
    
        tcp::resolver resolver(io_service);
        tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
        tcp::resolver::iterator iterator = resolver.resolve(query);
    
        tcp::socket s(io_service);
        s.connect(*iterator);
    
        std::cout << "sizeof uint32_t=" << sizeof(uint32_t) << std::endl;
    
        uint32_t len = 1234;
        std::cout << "len=" << len << std::endl;
    
        // uint => char 4
        char char_len[4];
        char_len[0] = (len >> 0);
        char_len[1] = (len >> 8);
        char_len[2] = (len >> 16);
        char_len[3] = (len >> 24);
    
        std::cout << "char[4] len=[" 
            << char_len[0] << ',' << char_len[1] << ',' 
            << char_len[2] << ',' << char_len[3] << ']' 
            << std::endl;
    
        // char 4 => uint
        uint32_t uint_len = *(reinterpret_cast<uint32_t *>( char_len ));
        std::cout << "uint len=" << uint_len << std::endl;
    
        // network bytes order
        uint32_t net_len = htonl( len );
        std::cout << "net_len=" << net_len << std::endl;
    
        // uint => char 4
        char net_char_len[4];
        net_char_len[0] = (net_len >> 0);
        net_char_len[1] = (net_len >> 8);
        net_char_len[2] = (net_len >> 16);
        net_char_len[3] = (net_len >> 24);
    
        std::cout << "net char[4] len=[" 
            << net_char_len[0] << ',' << net_char_len[1] << ',' 
            << net_char_len[2] << ',' << net_char_len[3] << ']' 
            << std::endl;
    
        std::cout << "net char[4] len=[" 
            << (int)net_char_len[0] << ',' << (int)net_char_len[1] << ',' 
            << (int)net_char_len[2] << ',' << (int)net_char_len[3] << ']' 
            << std::endl;
    
    
        boost::asio::write(s, boost::asio::buffer( net_char_len, 4));
    
        /*
        char reply[max_length];
        size_t reply_length = boost::asio::read(s, boost::asio::buffer(reply, 1 ));
    
        std::cout << "Reply is: ";
        std::cout.write(reply, reply_length);
        std::cout << "\n";
        */
      }
      catch (std::exception& e)
      {
        std::cerr << "Exception: " << e.what() << "\n";
      }
    
      return 0;
    }
    

    SERVER:

    #include <cstdlib>
    #include <iostream>
    #include <boost/bind.hpp>
    #include <boost/smart_ptr.hpp>
    #include <boost/asio.hpp>
    #include <boost/thread.hpp>
    
    using boost::asio::ip::tcp;
    
    const int max_length = 1024;
    
    typedef boost::shared_ptr<tcp::socket> socket_ptr;
    
    void session(socket_ptr sock)
    {
      try
      {
        for (;;)
        {
          char data[max_length];
    
          boost::system::error_code error;
    
          uint32_t net_len;
          size_t len_len = sock->read_some( boost::asio::buffer( reinterpret_cast<char*>(&net_len), 4), error );
    
          if (error == boost::asio::error::eof)
            break; // Connection closed cleanly by peer.
          else if (error)
            throw boost::system::system_error(error); // Some other error.
    
          std::cout << "net len=" << net_len << std::endl;
    
          uint32_t len = ntohl( net_len );
          std::cout << "uint len=" << len << std::endl;
    
          //char reply = '1';
          //std::cout << "char len=" << char_len << std::endl;
          //boost::asio::write(*sock, boost::asio::buffer( &reply, size_t(1)));
        }
      }
      catch (std::exception& e)
      {
        std::cerr << "Exception in thread: " << e.what() << "\n";
      }
    }
    
    void server(boost::asio::io_service& io_service, short port)
    {
      tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
      for (;;)
      {
        socket_ptr sock(new tcp::socket(io_service));
        a.accept(*sock);
        boost::thread t(boost::bind(session, sock));
      }
    }
    
    int main(int argc, char* argv[])
    {
      try
      {
        if (argc != 2)
        {
          std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
          return 1;
        }
    
        boost::asio::io_service io_service;
    
        std::cout << "Started" << std::endl;
        std::cout << "sizeof uint32_t=" << sizeof(uint32_t) << std::endl;
        using namespace std; // For atoi.
        server(io_service, atoi(argv[1]));
      }
      catch (std::exception& e)
      {
        std::cerr << "Exception: " << e.what() << "\n";
      }
    
      return 0;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to receive data from a server application using boost asio's async_read()
So I am doing a lot of high performance network programming using Boost::Asio (or
I am trying to build a project using Boost's Asio and I am having
I have been trying to set the TTL on ICMP packets using the boost::asio::ip::unicast::hops
I'm want to check for incoming data packages on the serial port, using boost.asio
I have a socket server, written in C++ using boost::asio, and I'm sending data
I'm using C++/boost::asio under Win7. I'm trying to sniff trafic over a given TCP/IP
I'm trying to create an HTTP client using Boost Asio. I copied the sync
I am trying to Create a simple Tcp Server in C++ using Boost ASio
I'm trying to asynchronously resolve a ftp host using Boost.Asio. Here's what I've tried

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.