2009-10-26 40 views
1

我使用套接字将数据从本地机器发送到TCP,流模式下的远程。 在本地端的代码是:接收订单的套接字

​​

数据的大小为1MB左右,所以插座有可能将其划分到几个包。 虽然我在远端接收数据,但我必须单独收集数据,然后将它们组合在一起。 在远程侧的代码是:

// ----------- 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; 
    } 
} 

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

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

在此先感谢。

回答

1

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

+0

“泵”是什么意思? 你的意思是,每当我使用消息框时,所有的消息“已经发布到窗口的消息队列中”都会被执行? 对不起,你能否清楚解释一下。再次感谢。 – KenC 2009-10-26 05:35:18

+0

每个UI线程都有一个用于Windows消息的消息泵。如果您使用的是原始Win32 API,那么您的winmain会调用GetMessage,DispatchMessage等,并且您拥有自己的WndProc。如果你使用的是MFC,那么MFC库的一部分就是为你做的。无论哪种方式,无论您是否编码,您的UI线程都有一个消息泵。 MSDN有很多页面描述消息泵,并且它不适合这样的评论。 – 2009-10-26 06:25:46

+0

你的意思是,如果我不使用消息框,那么顺序是正确的?因为我尝试了很多次。如果我不使用MessageBox,顺序是没问题的,尽管我有点担心它。 – KenC 2009-10-26 09:21:04

0

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