使用C ++ / boost :: asio在网络帧中进行int / char转换

时间:2011-09-26 14:06:44

标签: c++ networking boost boost-asio

使用g ++和boost :: asio,我试图格式化包含要传输的数据大小的网络消息帧:

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

在一个32字节的Linux下使用asio阻塞tcp echo客户端/服务器的例子,我坚持在帧中传输正确的大小。客户端应该是Windows机器。

客户端:

#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;
}

应该用简单的脚本编译:

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

客户端无法解码长度,服务器似乎没有收到正确的irt。我错过了什么?

3 个答案:

答案 0 :(得分:1)

从我在你的代码中看到的,你实际上并没有发送网络字节顺序,你的发送语句就像:boost::asio::write(s, boost::asio::buffer(char_len, 4));char_len看起来像是在主机顺序中填充... < / p>

可能你应该提供日志声明的输出 - 这可能会让事情变得更清晰......

答案 1 :(得分:1)

一个问题似乎是客户端发送了一些数据,然后想要接收一些内容并将其发送回服务器,但是服务器执行2次读取然后发送一些内容。因此,第二个read()可能会收到0个字节。

此外,只要有一些字节可用,read()函数就会读取。在这种情况下,即使客户端执行2 write(),服务器也可以使用第一个read()读取所有字节,第二个read()仍然会看到0个字节。您必须根据协议处理存储在缓冲区中的数据。

您从len到char_len的转换将无法按预期工作。由于char_len数组包含字符,cout尝试在屏幕上显示字符,但是低于32的任何值都不可显示。如果要显示每个char的ASCII值,则必须在将它们提供给cout之前将它们转换为int。

你应该按原样发送“len”:

boost::asio::write(s, boost::asio::buffer(&len, 4));

但是我没有在你的样本中看到任何消息。我只看到客户端和服务器之间正在交换一些长度。

根据该代码,我可以说这一切。

编辑:我保留了字节顺序,保持响应时间短。

答案 2 :(得分:1)

我终于设法找到了什么问题。

在服务器代码的底部有一个残留的读取,这阻止了第二个读取正确的字节,就像所说的@PRouleau。

客户端也写了错误的变量,正如@Nim指出的那样。

sevrer的错误检查不在正确的位置。

最后我得到以下的outpout:

客户端:

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

服务器:

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

使用以下代码:

客户端:

#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;
}