[英]How can I print the requests in boost.asio?
我正在使用boost.asio
編寫一個簡單的服務器。 下面的代碼試圖做兩件事:
hello
但事實並非如此。
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main(){
try{
boost::asio::io_context ioc;
tcp::acceptor acceptor(ioc, tcp::endpoint(tcp::v4(), 1010));
for(;;){
tcp::socket socket(ioc);
acceptor.accept(socket);
boost::system::error_code err;
std::string buff;
socket.read_some(boost::asio::buffer(buff), err);
std::cout << buff << '\n';
boost::asio::write(socket, boost::asio::buffer("hello"),err);
}
}
catch (std::exception& e){
std::cerr << e.what() << '\n';
}
return 0;
}
當我運行服務器並使用curl
發送請求時,它沒有響應,只打印一個空行。
[amirreza@localhost ~]$ curl 127.0.0.1:1010
curl: (1) Received HTTP/0.9 when not allowed
[amirreza@localhost ~]$
在服務器端(2個空行):
[amirreza@localhost 2]$ sudo ./server
[sudo] password for amirreza:
在這里我有兩個問題:
hello
消息? 我還觀察了wireshark中服務器和curl之間發送和接收的數據包。 At first the tcp handshake will occur but when curl send the HTTP
request, the server respond a tcp packet with RST
flag to reset the connection.
我注意到的第一件事:
std::string buff; socket.read_some(boost::asio::buffer(buff), err);
這讀入一個空字符串:0 字節。 要么預留空間:
buff.resize(1024); socket.read_some(boost::asio::buffer(buff), err);
或使用具有組合讀取操作的動態緩沖區(請參閱下一個)
read_some 讀取任何可用的內容,不一定是一行。 有關更高級別的讀取操作,請參見read_until
std::string buff; read_until(socket, boost::asio::dynamic_buffer(buff), "\n");
處理錯誤。 在您的情況下,您可以簡單地刪除ec
變量,並依賴異常,因為您已經處理了這些
#include <boost/asio/buffer.hpp>
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
int main(){
try{
boost::asio::io_context ioc;
tcp::acceptor acceptor(ioc, tcp::endpoint(tcp::v4(), 11010));
for(;;) {
tcp::socket socket(ioc);
acceptor.accept(socket);
std::string buff;
auto bytes = read_until(socket, boost::asio::dynamic_buffer(buff), "\n");
std::cout << buff.substr(0, bytes) << std::flush;
boost::asio::write(socket, boost::asio::buffer("hello"));
}
}
catch (std::exception const& e){
std::cerr << e.what() << '\n';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.