C ++ - 在同一程序中运行一个服务器线程和一个客户端线程

时间:2014-05-19 10:25:28

标签: c++ multithreading client-server

我一直在尝试修改boost的日间服务器/客户端示例,以便在2个线程中运行,如下所示,但它不起作用:

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

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

std::string make_daytime_string()
{
  using namespace std; // For time_t, time and ctime;
  time_t now = time(0);
  return ctime(&now);
}

void ServerThread()
{
    boost::asio::io_service io_service;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));

    for (;;)
    {
        std::cout << "why?";
        tcp::socket socket(io_service);
        acceptor.accept(socket);
        std::string message = make_daytime_string();
        boost::system::error_code ignored_error;
        boost::asio::write(socket, boost::asio::buffer(message),
        boost::asio::transfer_all(), ignored_error);
    }

}

void ClientThread()
{
    try
  {
    boost::asio::io_service io_service;

    std::string hostString;

    std::cout << "Please enter the host: ";
    std::cin >> hostString;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(hostString, "daytime");
    tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

    tcp::socket socket(io_service);
    boost::asio::connect(socket, endpoint_iterator);
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }
}

int main()
{
  boost::thread s(&ServerThread);
  boost::thread c(&ClientThread);

  c.join();
  s.join();

  return 0;
}

两个线程一个接一个地运行,不能正确处理。我想我需要沿着叉子做一些事情?请帮忙告诉我代码有什么问题,谢谢。

1 个答案:

答案 0 :(得分:1)

在您的客户端中,您遗漏了接收数据的代码部分。连接后把它放进去:

for (;;)
{
    boost::array<char, 128> buf;
    boost::system::error_code error;

    size_t len = socket.read_some(boost::asio::buffer(buf), error);
    if (error == boost::asio::error::eof)
        break; // Connection closed cleanly by peer.
    else if (error)
        throw boost::system::system_error(error);
    std::cout.write(buf.data(), len);
}

您还需要包含boost / array.hpp。