以下是一个dll库,目的是向指定的IP地址中发送命令,并得到返回值,问题是在发送了命令之后,socket是自动调用Onreceive来获得返回值“Result_value”的,而主程序还在继续,如何是主程序暂停来获得返回值?(不知道有没有说清楚?请看源代码中的注释!!)主程序代码:
extern "C" __declspec(dllexport)long WINAPI GetOth2Status(long CNCType, char *IPAddress, unsigned short PortNo, long TimeOut, StatusData* data ) ;
long WINAPI GetOth2Status( long CNCType,
char *IPAddress,
unsigned short PortNo,
long TimeOut, StatusData *data )
{ HKEY hKey; LPBYTE AlarmNo=new BYTE[4];
DWORD type=REG_SZ;
DWORD length=4;   CString m_StrStatus;
CString cTemp; StatusData MyBuf ;
memset( data, 0, sizeof( StatusData ) ) ;
memset( &MyBuf, 0, sizeof( StatusData ) ) ;
if (!AfxSocketInit())
{
theApp.m_dataSocket->Close();
delete theApp.m_dataSocket;
return -1;
} if (!theApp.m_dataSocket->connect(IPAddress, PortNo))
{
//theApp.m_dataSocket.Close();
theApp.m_dataSocket->Close();
delete theApp.m_dataSocket;
return -1;
         }         //通过socket向sever端发送命令 
if(theApp.m_dataSocket->writeCommand("<ncda><req>yes</req><var>status</var></ncda>")==false)    
         {
theApp.m_dataSocket->Close();
delete theApp.m_dataSocket;
//AfxMessageBox(m_StrStatus);
return -1;
}
//获得返回值(如何等到onreceive函数中真正获得了返回值后在进行这个赋值操作?)
MyBuf.status = theApp.m_dataSocket->Result_value;
         memcpy( data, &MyBuf, sizeof( StatusData ) ) ;
return 0 ; //Power ON
}//socket自动调用的函数
void CDataSocket::OnReceive(int nErrorCode) 
{
//int i=1;
// TODO: Add your specialized code here and/or call the base class
// StatusData* MyStatus;
CMapStringToString* data = new CMapStringToString;
CString value;
// char buffer[20];
char buff[4096];
int nRead;
nRead = Receive(buff, 4096); 
buff[nRead] = 0; //terminate the string
   
if (nRead == SOCKET_ERROR)
{
if (GetLastError() != WSAEWOULDBLOCK) 
{
AfxMessageBox ("Error occurred");
Close();
}
}
else
{
                  Result_value =buff;

}

CSocket::OnReceive(nErrorCode);
}

解决方案 »

  1.   

    单步跟踪一下下面这行:
    nRead = Receive(buff, 4096); 看看服务程序有没有进到这?服务器有没有返回数据?
      

  2.   

    楼上的说的这些都是正常的,问题处在如何在主程序中等到子程序响应了onreceive后在继续运行
      

  3.   

    弄个循环不就行了吗?
    while(theApp.m_dataSocket->Result_value)
    {
    MyBuf.status = theApp.m_dataSocket->Result_value;
             memcat( data, &MyBuf, sizeof( StatusData ) ) ;
    }