这实际上是我在套接字编程中的第一个程序,而不是复制粘贴教程代码并获得乐趣。无论如何它不起作用。我想我已经仔细阅读了文档,但可能还不够。我怀疑我在socket::read_some()
使用了read_message()
因为我的问题程序在阅读部分停止了。我认为我使用它的方式应该没问题,因为socket::read_some()
的文档声明"函数调用将阻塞,直到成功读取一个或多个字节的数据,或者直到发生错误。&# 34;以下是我的代码。任何帮助表示赞赏。
void read_message(std::string& message, boost::asio::ip::tcp::socket& socket)
{
std::stringstream message_stream;
while (true)
{
std::array<char, 128> buffer;
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buffer), error);
if (error == boost::asio::error::eof)
{
break;
}
message_stream.write(buffer.data(), len);
}
message = message_stream.str();
}
server.cpp 的
int main()
{
while (true)
{
boost::asio::io_service io_service;
boost::asio::ip::tcp::acceptor acceptor(io_service, boost::asio::ip::tcp::endpoint(
boost::asio::ip::tcp::v4(), 9999));
boost::asio::ip::tcp::socket socket(io_service);
acceptor.accept(socket);
std::cout << "connected with client, waiting for a message\n";
std::string message;
read_message(message, socket);
boost::asio::ip::tcp::endpoint endpoint = socket.remote_endpoint();
std::cout << "message received from " << endpoint.address().to_string() <<
':' << endpoint.port() << '\n' << message << '\n';
boost::asio::write(socket, boost::asio::buffer(message));
if (message.compare("quit") == 0)
{
break;
}
}
return EXIT_SUCCESS;
}
client.cpp 的
int main()
{
while (true)
{
std::cout << "your message to be sent: ";
std::string message;
std::getline(std::cin, message);
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::ip::tcp::resolver::query query("localhost", "9999");
boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
boost::asio::ip::tcp::socket socket(io_service);
boost::asio::connect(socket, endpoint_iterator);
std::cout << "connected to server\n";
boost::asio::write(socket, boost::asio::buffer(message));
read_message(message, socket);
std::cout << "message received from server: " << message << '\n';
if (message.compare("quit") == 0)
{
break;
}
}
return EXIT_SUCCESS;
}
答案 0 :(得分:4)
问题出在read_message
函数:你读到eof
,但只有当套接字关闭时才会得到eof
。
也许你打算在遇到某个分隔符时从read_message
返回,例如。 '\ N'?然后,您可以手动检查缓冲区,或使用read_until
函数。
使用read_until
函数,read_message
将如下所示:
void read_message(std::string& message, boost::asio::ip::tcp::socket& socket)
{
std::stringstream message_stream;
boost::asio::streambuf buffer;
boost::system::error_code error;
size_t len = read_until(socket, buffer, '\n', error);
if (len)
{
message_stream.write(boost::asio::buffer_cast<const char *>(buffer.data()), len);
message = message_stream.str();
}
}
请记住将“\ n”附加到您从客户端发送的邮件中:
//...
std::cout << "connected to server\n";
boost::asio::write(socket, boost::asio::buffer(message + '\n'));
read_message(message, socket);
//...