简体   繁体   English

如何检查Boost套接字的write_some方法是否结束

[英]How to check boost socket write_some method ends or not

I am trying to send some data by using boost socket. 我正在尝试通过使用Boost套接字发送一些数据。 TCPClient class's role is to make a connection cna can send data throw sendMessage method. TCPClient类的作用是使连接cna可以将发送数据的方法抛出sendMessage方法。

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 客户端main()代码

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

under code is snedMessage method. 在代码下是snedMessage方法。

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. 您的sendMessage()函数编写不正确。 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. 您不能指望套接字会一次发送所有数据,您需要一个循环来尝试发送,检查发送了多少字节,偏移缓冲区(当然totalLength相应地更新totalLength ),并在必要时重复直到发送totalLength所有数据。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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