Mla*_*jic 6 c++ json boost http
我需要编写一个命令行客户端来通过服务器播放tic-tac-toe.服务器接受http请求并将json发送回我的客户端.我正在寻找一种快速方式来发送http请求并使用boost库接收json作为字符串.
example http request = "http://???/newGame?name=david"
example json response = "\"status\":\"okay\", \"id\":\"game-23\", \"letter\":2"
Run Code Online (Sandbox Code Playgroud)
符合描述的最简单的事情:
#include <boost/asio.hpp>
#include <iostream>
int main() {
boost::system::error_code ec;
using namespace boost::asio;
// what we need
io_service svc;
ip::tcp::socket sock(svc);
sock.connect({ {}, 8087 }); // http://localhost:8087 for testing
// send request
std::string request("GET /newGame?name=david HTTP/1.1\r\n\r\n");
sock.send(buffer(request));
// read response
std::string response;
do {
char buf[1024];
size_t bytes_transferred = sock.receive(buffer(buf), {}, ec);
if (!ec) response.append(buf, buf + bytes_transferred);
} while (!ec);
// print and exit
std::cout << "Response received: '" << response << "'\n";
}
Run Code Online (Sandbox Code Playgroud)
这将收到完整的回复.您可以使用虚拟服务器进行测试:(
还可以在Coliru上运行):
netcat -l localhost 8087 <<< '"status":"okay", "id":"game-23", "letter":2'
Run Code Online (Sandbox Code Playgroud)
这将显示收到请求,并且响应将由我们上面的客户端代码写出.
请注意,对于更多想法,您可以查看示例http://www.boost.org/doc/libs/release/doc/html/boost_asio/examples.html(尽管他们专注于异步通信,因为这是主题Asio图书馆)
归档时间: |
|
查看次数: |
20435 次 |
最近记录: |