使用boost-asio在C ++和Python程序之间的客户端服务器

时间:2014-06-10 19:53:19

标签: python c++ sockets boost-asio

我是C ++的初学者。请给我建议并说出我做错了什么。我必须创建客户端服务器通信Python客户端,C ++服务器。我在C ++上创建了服务器,但我只能使用telnet进行通信。我的代码:

#include <iostream>
#include <string>
#include <boost/asio.hpp>

int main()
{
  const int SERVER_PORT = 50013;

  try {
    boost::asio::io_service io_service;
    boost::asio::ip::tcp::endpoint     endpoint(boost::asio::ip::tcp::v4(),SERVER_PORT);
    boost::asio::ip::tcp::acceptor acceptor(io_service, endpoint);
    boost::asio::ip::tcp::socket socket(io_service);

    std::cout << "Server ready" << std::endl;
    {
      acceptor.accept(socket);
      int foo [5] = { 16, 2, 77, 40, 12071 }; 
      boost::asio::write(socket, boost::asio::buffer(foo));
      socket.close();
    }
  }
  catch(std::exception& ex)
  {
    std::cerr << "Exception: " << ex.what() <<std::endl;
  }
  return 0;
}

我想通过客户端Python与它沟通:

#!/usr/bin/python           # This is client.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 50013                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close()                   # Close the socket when done

但我的客户端没有任何结果

1 个答案:

答案 0 :(得分:2)

  

但我的客户端没有任何结果

你有,但你解释错了:

s.connect((host, port))
print binascii.hexlify(s.recv(1024))

结果:

10000000020000004d00000028000000272f0000