1

我试图通过发送5,000字节字符包boost::asio。但我得到了错误:buffer overflow。有没有办法自动提升拆分或我必须手动执行?

这是数据包代码:

char * CPlayerCharacter::getEnviPacket() //len 5824
{
 char * buffer = new char[5824];
 char xf[4];
 char yf[4];
 sprintf(xf, "%f", x);
 sprintf(yf, "%f", y);
 for(int i =0;i<5824;i++)
 {
  buffer[i] = 0x00;
 }
 buffer[0] = 5824 & 0xff;
 buffer[1] = 5824 >> 8 & 0xff;
 buffer[4] = 4; //minor id
 buffer[6] = 1; //major id
 buffer[8] = 1;
 buffer[12] = id & 0xff;
 buffer[13] = (id>>8)  & 0xff;
 buffer[14] = (id>>16)  & 0xff;
 buffer[15] = (id>>24)  & 0xff;
 buffer[20] = mapid;//map id
 buffer[24] = 18;
 buffer[28] = 0x0a;
 buffer[29] = 0x0f;
 buffer[30] = 0x16;
 for(int i =0;i<4;i++)
 {
  buffer[5800+i] = xf[i];
  buffer[5804+i] = yf[i];
 }
 buffer[5808] = 0x0c;
 buffer[5813] = 0x9d;
 buffer[5814] = 0x0f;
 buffer[5815] = 0xbf;
 buffer[5822] = 0x60;
 buffer[5823] = 0x2a;
 return buffer;
}

这是处理程序代码:

void CConnection::handle_enter_world(int packetlen)
{
 Decryptor dec;
 char buffer[packetlen];
 boost::asio::async_read(socket_,
        boost::asio::buffer(buffer, packetlen),
        boost::bind(
          &CConnection::nothing, shared_from_this()));  
 char * decrypted = decrypted = dec.decrypt((char*)&buffer, packetlen); 
 asynchronousSend(pl.characters[(int)decrypted[0]].getEnviPacket(), 5824);
}

这是 asynchronousSend 函数:

 void CConnection::asynchronousSend(char * data, int len)
 {
    boost::asio::async_write(socket_, boost::asio::buffer(data, len), boost::bind(&CConnection::handle_write, shared_from_this()));
    delete [] data;
 }

谢谢。

4

1 回答 1

0

您正在尝试以同步方式使用异步async_read调用async_write。这行不通。

void CConnection::handle_enter_world(int packetlen)
{
 Decryptor dec;
 char buffer[packetlen];
 boost::asio::async_read(socket_,
        boost::asio::buffer(buffer, packetlen),
        boost::bind(
          &CConnection::nothing, shared_from_this()));

 // RIGHT NOW -- nothing has been read yet.  
 // ...
}

读取完成后,将通过您提供的回调函数(CConnection::nothing)通知您。那就是您需要进行“解密”的地方。

另一个问题:

void CConnection::asynchronousSend(char * data, int len)
 {
    boost::asio::async_write(socket_, boost::asio::buffer(data, len), boost::bind(&CConnection::handle_write, shared_from_this()));
    // RIGHT NOW -- nothing has been written yet
    delete [] data;
 }

类似的问题在这里。编写完成后,将通过您提供的回调函数(CConnection::handle_write)通知您。通过过早调用delete[]data您发送的数据将被损坏。您需要在回调函数中删除该内存(或者更好的是,将该内存也设为共享指针)。

如果您希望代码同步执行,您可以改用同步调用boost::asio::writeboost::asio::read(或read_until)。

于 2013-05-31T15:59:39.850 回答