什么是通过tcp将数据流存储到大型数组中的最佳方法?

时间:2013-07-09 08:54:31

标签: c++ c visual-c++ tcpsocket

我想通过TCP连接将数据流存储到大型数组中,我该怎么做?

我的代码:

int iResult, count;
int recvbuflen = 512;
char buff[4096]={0};
char recvbuf[512] = {0};

.................

count = 0;

do {

    iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {

                count+=iResult;

                //code to store in the buff[] array until reach to 4096 byte
                //that's what i need
                //for example: each time bind or add the recvbuf[] array at 
                //the end of buff[] array until reach to 4096 byte. 

                if(count == 4096)
                {
                  //do the next process
                  count = 0; 
                }
              }
    }while(iResult > 0);

任何帮助。

1 个答案:

答案 0 :(得分:4)

你可以直接回到你的大缓冲区并每次都添加一个偏移量:

iRes = recv(ClientSocket, (buff+offset), 4096-offset, 0);

等。注意不要溢出缓冲区。如果您需要单独接收数据并根据内容将它们添加到缓冲区,只需将recvbuf memcpy到缓冲区(带偏移量)。偏移量只是跟踪,直到缓冲区已经填满。 再次,留意缓冲区溢出。