刚开始用C++,有个Scoket的问题想请教。在TestApp.cpp的InitInstance()方法中调用了AfxSocketInit(),文件中还有另外一个方法CanConnectToServer()提供给其他窗体调用,刚开始我用的是CAsyncSocket,后来发现程序刚启动时调用这个方法返回结果为true,闲置一段时间后,却返回false,所以就改成了CSocket。改成CSocket后,发现服务器端程序关闭之后调用这个方法还是返回true。请问是什么原因?
bool CTestApp::CanConnectToServer()
{
CString strIPAddr = _T("10.10.6.235");
int port = 2439;
CSocket* pSocket = new CSocket(); pSocket->Create();
if(pSocket->Connect(strIPAddr,port))
{
pSocket->Close();
delete pSocket;
return true;
}
else
{
delete pSocket;
return false;
}
}

解决方案 »

  1.   

    #include <iostream> 
    #include <afxtempl.h> 
    #include <afxsock.h>#ifdef _DEBUG
    #define new DEBUG_NEW
    #endif
    // 唯一的应用程序对象CWinApp theApp;using namespace std;bool CanConnectToServer()
    {
    CString strIPAddr = _T("www.sina.com.cn");
    int port = 80;
    CSocket* pSocket = new CSocket(); pSocket->Create();
    if(pSocket->Connect(strIPAddr,port))
    {
    pSocket->Close();
    delete pSocket;
    return true;
    }
    else
    {
    delete pSocket;
    return false;
    }
    }class AutoInitSock : public WSADATA
    {
    public:
    static bool Initialise()
    {
    static AutoInitSock self_; return self_.succ();
    }public:
    bool succ() const{return has_initialised_;}private:
    AutoInitSock()
    : has_initialised_(false)
    {
    if(0 == WSAStartup(MAKEWORD(2, 2), this))
    {
    has_initialised_ = true;
    }
    } bool has_initialised_;
    };
    int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    {
    int nRetCode = 0; // 初始化 MFC 并在失败时显示错误
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
    // TODO: 更改错误代码以符合您的需要
    _tprintf(_T("错误: MFC 初始化失败\n"));
    nRetCode = 1;
    }
    else
    {
    // TODO: 在此处为应用程序的行为编写代码。 VERIFY(AutoInitSock::Initialise()); cout << CanConnectToServer() << endl; } return nRetCode;
    }
    好像没你的说的问题啊?
      

  2.   

    谢谢回复!我说的是“服务器端程序关闭之后调用这个方法还是返回true”,你连接你本机的IIS,先调用这个方法,再关闭IIS服务后再测试看看,我刚试过,是有问题的。
      

  3.   

    呵呵,我试试了,关了之后返回就是0了(apache)。
      

  4.   

    我的程序是在Windows Mobile移动设备上使用,但应该和这个没有关系。
      

  5.   

    晕。
    windows mobile有没有使用网关?
      

  6.   

    没有啊,直接使用ActiveSync连接到PC上,那段代码我在PC上测试没有问题,放到Windows Mobile中后就有问题。
      

  7.   

    查了一下资料,说WinCE中需要使用CCeSocket,但是改为这个后服务器未启动也返回true。