How to copy byte buffer in Poco C ++?

Hi, I am trying to write a TCP connection in poco. the client sends a packet with these fields:

packetSize : int date : int ID : int

therefore, the first 4 bytes contain the packet size. on the receiving side, I have this code:

int packetSize = 0;
char *bufferHeader = new char[4];

// receive 4 bytes that contains packetsize here
socket().receiveBytes(bufferHeader, sizeof(bufferHeader), MSG_WAITALL);

Poco::MemoryInputStream *inStreamHeader = new Poco::MemoryInputStream(bufferHeader, sizeof(bufferHeader));
Poco::BinaryReader *BinaryReaderHeader = new Poco::BinaryReader(*inStreamHeader);

(*BinaryReaderHeader) >> packetSize; // now we have the full packet size

Now I am trying to save all remaining incoming bytes into one array for future binary reading:

int ID = 0;
int date = 0;
int availableBytes = 0;
int readedBytes = 0;
char *body = new char[packetSize - 4];

do
{
    char *bytes = new char[packetSize - 4];

    availableBytes = socket().receiveBytes(bytes, sizeof(bytes), MSG_WAITALL);

    if (availableBytes == 0)
        break;

    memcpy(body + readedBytes, bytes, availableBytes);

    readedBytes += availableBytes;

} while (availableBytes > 0);

Poco::MemoryInputStream *inStream = new Poco::MemoryInputStream(body, sizeof(body));
Poco::BinaryReader *BinaryReader = new Poco::BinaryReader(*inStream);

(*BinaryReader) >> date;
(*BinaryReader) >> ID;

cout << "date :" << date << endl;
cout << "ID :" << ID << endl;

, , 4 (). , . , . , memystream, , , !!

, , ?

alot

+4
1

. , , , . sizeof char[] sizeof char *; - , - : 4 8 , .

,

availableBytes = socket().receiveBytes(bytes, sizeof(bytes), MSG_WAITALL);

4 . , , .

Poco::MemoryInputStream *inStream = new Poco::MemoryInputStream(body, sizeof(body));

sizeof(char *) inStream

sizeof(body) sizeof(bytes) packetSize - 4.

P.s:

: .

 char *bytes = new char[packetSize - 4];

packetSize - 4. do ... while().

bytes (togheter body).

2016.03.17

(: )

size_t  toRead  = packetSize - 4U;
size_t  totRead = 0U;
size_t  nowRead;

char * body = new char[toRead];

do 
{
  nowRead += socket().receiveBytes(body+totRead, toRead-totRead,
                MSG_WAITALL);

  if ( 0 == nowRead )
     throw std::runtime_error("shutdown from receiveBytes()");

  totRead += nowRead;

} while ( totRead < toRead );

Poco::MemoryInputStream *inStream = new Poco::MemoryInputStream(body, 
                                           toRead);

delete[] body;

body = NULL;
+1

All Articles