Reputation: 153
client code
#include <cstdlib>
#include <iostream>
#include <memory>
#include <utility>
#include <boost/asio.hpp>
#include <string>
#include <boost/array.hpp>
using namespace std;
using namespace boost::asio;
int main(int argc, char* argv[])
{
io_service service;
ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 2001);
ip::tcp::socket sock(service);
sock.connect(ep);
boost::asio::streambuf sb;
boost::system::error_code ec;
size_t len;
while (true)
{
//write data
sock.write_some(buffer("ok", 2));
//read data
read(sock, sb, transfer_all(),ec);
//handle error
if (ec && ec != error::eof) {
std::cout << "receive failed: " << ec.message() << std::endl;
}
else {
const char* data = buffer_cast<const char*>(sb.data());
std::cout << data << std::endl;
}
}
return 0;
}
server code
import socket
import threading
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(("127.0.0.1",2001))
s.listen(5)
cons = []
print "begin....."
while True:
con,addr = s.accept()
#cons.append(con)
print con
while True:
data = con.recv(1024)
if not data:
con.close()
break;
print data
con.send("123")
s.close()
Client can send "ok" to the server, but it cannot receive "123" from the server.
If I use a client written in python, the server and client can communicate well.
Could someone tell the reason about this mistake?
Upvotes: 0
Views: 427
Reputation: 309
Use the tcp::socket::read_some
method. This method blocks until something gets received to the socket and then reads the data (while the read(...) function reads the whole file/socket until EOF, which only occurs if the connection drops)
You can read up the usage here.
Example:
std::string recbuf;
while (true)
{
//write data
sock.write_some(buffer("ok", 2));
//read data
sock.read_some(buffer(recbuf, 1024), ec);
//handle error
if (ec && ec != error::eof) {
std::cout << "receive failed: " << ec.message() << std::endl;
}
else {
std::cout << recbuf << std::endl;
}
}
Upvotes: 1
Reputation: 153
I have found similar question boost::asio::ip::tcp::socket doesn't read anything.
Using read_until can solve this question.
Upvotes: 0