接收套接字顺序

时间:2009-10-26 03:46:32

标签: windows tcp sockets send recv

我使用socket在TCP,流模式下将数据从本地机器发送到远程。 本地代码是:

// ----------- Local
send(sd, pData, iSize, 0);  // send data

数据的大小约为1Mb,因此socket可能会将其分成几个数据包。 当我收到远程数据时,我必须单独接收数据,然后将它们组合在一起。 远程端的代码是:

// ----------- Remote : Receiving data
int         iSizeThis(0);// size of a single separated data
static int  iSizeAcc(0);//size of the total data I have already got.
static int  iDataSize(0);// size of the original data.

// Get size
if (iDataSize <= 0)
{
    if ( (iSizeThis = recv(cli_sd, (char*)&iDataSize, 4, MSG_PEEK)) == 0) {
        ....
    } else if (iSizeThis == SOCKET_ERROR) {
        ....
    } else {
        // Allocates memory
        if (iDataSize > 0)
            pData = realloc(pData, iDataSize);
    }

} else if (iSizeAcc < iDataSize){

    // Get data.
    // The size of the data is about 1Mb, so socket will divide it to several packets.
    // I have to recieve the data separately, and then combine them together.

    iSizeThis = recv(cli_sd, ((char*)pData) + iSizeAcc, iDataSize - iSizeAcc, 0);

    iSizeAcc += iSizeThis;

    //{// If I uncomment this block, the recieving order will be reversed. Why?????
    //  static int i(0);
    //  std::ostringstream oss;
    //  oss << i++ << "\n\n";
    //  oss << "iSizeThis : " << iSizeThis << "\n";
    //  oss << "iSizeAcc : " << iSizeAcc << "\n";
    //  oss << "iDataSize : " << iDataSize << "\n";
    //  ::MessageBoxA(this->GetSafeHwnd(), oss.str().c_str(), "---", 0);
    //}

    // If all the fragment are combined into pData, the save it to a file.
    if (iSizeAcc >= iDataSize){
        // Save to file
        FILE * pFile;
        pFile = fopen ("CCC.dat","wb");
        if (pFile != NULL){
            fwrite ( ((char*)pData)+4 , 1 , iDataSize-4 , pFile );
            fclose (pFile);
        }

        iSizeAcc = 0;
        iDataSize = 0;
    }
}

奇怪的是。如果我取消注释远程端的消息块,则接收顺序将被反转。 因此,远程数据的结果不正确。

为什么呢? (我怎样才能得到每个片段的正确顺序?)

提前致谢。

2 个答案:

答案 0 :(得分:1)

当MessageBoxA函数正在执行时,它会将消息泵送到您的窗口。无论你的线程是否期望它们,MessageBoxA都会将它们发送给你。

答案 1 :(得分:0)

在接收循环中调用MessageBoxA(阻塞,模态对话框)是一个根本上有缺陷的想法。如果要查看值,请在调试器中运行它,将它们打印到对话框(例如文本字段),将它们输出到控制台或将它们转储到文件中。