简体   繁体   中英

How to check boost socket write_some method ends or not

I am trying to send some data by using boost socket. TCPClient class's role is to make a connection cna can send data throw sendMessage method.

When I executed under code it does not work. However, it works when I debug it. I think the problem is timing.

delete[] msg; works before sending msg.(just my thought)

so, I want to check whether msg is sent or not. or any other good way.

client main() code

TCPClient *client = new TCPClient(ip, port);
client->sendMessage((char *)msg, 64 + headerLength + bodyLength);
delete[] msg;

under code is snedMessage method.

void TCPClient::sendMessage(const char *message, int totalLength) throw(boost::system::system_error) {

if(false == isConnected())
    setConnection();

boost::system::error_code error;
this->socket.get()->write_some(boost::asio::buffer(message, totalLength), error);

if(error){
        //do something
}

}

Your sendMessage() function is written incorrectly. You cannot expect that socket will send all of your data at once, you need a loop where you try to send, check how many bytes were sent, offset buffer (and update totalLength accordingly of course) if necessary and repeat until all data is sent. Or interrupt if there is error condition. You try to send only once, ignore result and assume that if there is no error then all data was sent. This is not a case. Stream socket may send one or two or whatever amount of bytes at a time, and your code needs to handle that.

Your code should be something like this:

while( totalLength ) {
    boost::system::error_code error;
    auto sz = this->socket.get()->write_some(boost::asio::buffer(message, totalLength), error);

    if(error){
        //do something and interrupt the loop
    }
    totalLength -= sz;
    message += sz;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM