I'm using boost.asio
to write a simple server. The code below is trying to do 2 things:
hello
but it does not.
#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;
}
When I run the server and send a request using curl
it does not respond and only print an empty line.
[amirreza@localhost ~]$ curl 127.0.0.1:1010
curl: (1) Received HTTP/0.9 when not allowed
[amirreza@localhost ~]$
and in server side (2 empty line):
[amirreza@localhost 2]$ sudo ./server
[sudo] password for amirreza:
here I have 2 questions:
hello
message? I also observed packets sent and received between server and curl in wireshark. 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.
First thing I notice:
std::string buff; socket.read_some(boost::asio::buffer(buff), err);
This reads into an empty string: 0 bytes. Either reserve space:
buff.resize(1024); socket.read_some(boost::asio::buffer(buff), err);
or use a dynamic buffer with a composed read operation (see next)
read_some reads whatever is available, not necessarily a line. see read_until
for higher level read operations
std::string buff; read_until(socket, boost::asio::dynamic_buffer(buff), "\n");
handle errors. In your case you could simply remove the ec
variable, and rely on exceptions since you alreaady handle those
#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';
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.