我是新手来升级库,因此在修改此函数时需要一些帮助来从服务器获取返回消息。
如果删除代码的第二部分,服务器就能从客户端读取消息。
但是当我尝试从服务器读取返回消息时(第二部分中的代码),服务器出错"无法读取套接字"
void send_something(std::string host, int port, std::string message)
{
boost::asio::io_service ios;
boost::asio::ip::tcp::endpoint
endpoint(boost::asio::ip::address::from_string(host), port);
boost::asio::ip::tcp::socket socket(ios);
socket.connect(endpoint);
boost::array<char, 128> buf;
std::copy(message.begin(),message.end(),buf.begin());
boost::system::error_code error;
socket.write_some(boost::asio::buffer(buf, message.size()), 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); // Some other error.
}
std::cout.write(buf.data(), len);
}
答案 0 :(得分:1)
这是执行您想要的代码。请注意,我没有实现任何从服务器接收数据的框架,因此您可能会或可能不会收到完整的数据。
如果您想要从服务器接收完整的消息,您可以循环read_some
,就像它为write_some
所做的一样,直到您的阅读邮件大小等于您期待着。
还有其他类型的阅读,例如read_until
,您可以让asio收集响应,直到它看到指定的模式,例如新行(&#39; \ n&#39;或\ r \ n)中。
#include <iostream>
#include <array>
#include <string>
#include <system_error>
#include <asio.hpp>
void send_something(std::string host, int port, std::string message)
{
asio::io_service ios;
asio::ip::tcp::endpoint
endpoint(asio::ip::address::from_string(host), port);
asio::ip::tcp::socket socket(ios);
socket.connect(endpoint);
std::error_code error;
size_t len = 0;
// Write the complete message
while (len < message.length()) {
len += socket.write_some(asio::buffer(message), error);
}
std::array<char, 128> buf;
socket.read_some(asio::buffer(buf), error);
if (error == asio::error::eof)
{
std::cout << "Connection closed by server\n";
}
else if (error)
{
std::cout << "ERROR in connection" << std::endl;
return;
}
std::cout << "Received: " << buf.data() << std::endl;
}
int main() {
send_something("127.0.0.1", 7869, "Hello!");
return 0;
}
TEST ::
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket as sock
>>> sd = sock.socket(sock.AF_INET, sock.SOCK_STREAM)
>>> sd
<socket._socketobject object at 0x1088d2c20>
>>> sd.bind(("localhost", 7869))
>>> sd.listen(2)
>>> c, a = sd.accept()
>>> c
<socket._socketobject object at 0x1088d2c90>
>>> buf = c.recv(512)
>>> buf
'Hello!'
>>>
>>> c.send("Cool!")
5
MacBook-Pro:asio_test amuralid$ g++ -g -std=c++14 -I ~/asio-master/asio/include/ -o client_read_so client_read_so.cc -pthread
MacBook-Pro:asio_test amuralid$ ./client_read_so
Received: Cool!