开发者

reading from boost asio socket and printing to terminal

开发者 https://www.devze.com 2023-03-17 00:12 出处:网络
I want to use boost asio sockets to send a message from the server to the client and then print it out to the client terminal.I am trying to send the message \"hello\".It doesn\'t work.How can i fix t

I want to use boost asio sockets to send a message from the server to the client and then print it out to the client terminal. I am trying to send the message "hello". It doesn't work. How can i fix this? Thanks!

client:

#include <boost/asio.hpp>
#include <iostream>
#include <string>
using namespace std;
int main (int argc, char* argv[]) {
 try {
  boost::asio::io_service io_service;
  boost::asio::ip::tcp::resolver::query query("localhost", "41005");
  boost::asio::ip::tcp::resolver resolver(io_service);
  boost::asio::ip::tcp::resolver::iterator destination = resolver.resolve(query);
  boost::asio::ip::tcp::resolver::iterator end ;
  boost::asio::ip::tcp::endpoint endpoint;


  while ( destination != end ) {
     endpoint = *destination++;
     std::cout<<endpoint<<std::endl;
  }

  boost::asio::ip::tcp::socket socket(io_service);
  socket.connect(endpoint);
  boost::array< char, 128 > buf;
  boost::system::error_code error;
  std::size_t length = boost::asio::read(socket, boost::asio::buffer(buf, 512), boost::asio::transfer_all(), error);
  cout << length;
 }
 catch (std::exception& e)
 {
   std::cerr << e.what() << std::endl;
 }
 return 0;
}

server:

#include <boost/asio.hpp>
#include <iostream>
#include <string>
using namespace std;

int main () {

try {
  boost::asi开发者_运维百科o::io_service io_service;
  boost::asio::ip::tcp::acceptor acceptor(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 41005));

  for (; ;) {
     std::cout<<"Listening to"<<std::endl;
     boost::asio::ip::tcp::socket socket(io_service);
     acceptor.accept(socket);

     std::string message = "hello";
     boost::system::error_code ignored_error;
     boost::asio::write(socket, boost::asio::buffer(message), boost::asio::transfer_all(), ignored_error);
  }
}
catch (std::exception& e)
{
  std::cerr << e.what() << std::endl;
}
return 0;

}


classic error: the "acceptor.accept" method is a blocking call, so the hello part is never called.

Our COut friend would help you, as allways:

... std::cout<<"Sending hello"<

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号