none
请教socket重启成功,但连接失败问题 RRS feed

  • 问题

  • CUsbEngine::CUsbEngine()
    {
    m_status = EBeforeConnect;
    m_receiveThread = NULL;
    m_bGprsTest = false;
    m_acceptThread = NULL;
    INT iRet = WSAStartup(MAKEWORD(2,2), &wsaData);
        if(NO_ERROR != iRet)
    {
    hr = E_FAIL;
    fSockInitialized = FALSE;
    return;
    }
    // Create a socket.
        mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if(INVALID_SOCKET == mySocket)
    {
    iRet = WSAGetLastError();
    fSockInitialized = false;
    hr = HRESULT_FROM_WIN32(iRet);
    return;
        }
    PrintLog("fsock True");
        fSockInitialized = TRUE;
    m_receiveBuffer = new char[MaxUsbData];
    }
    CUsbEngine::~CUsbEngine()
    {
      Stop(0);
      delete m_receiveBuffer;
      m_receiveBuffer = NULL;
    }
    void CUsbEngine::Stop(int nErrorCode)
    {
    m_status = EBeforeConnect;
    if(m_receiveThread)
    {
    m_receiveThread->ResumeThread();
    }
    if(sockConn!= NULL)
    {
    closesocket(sockConn);
    sockConn = NULL;
    }
    if (mySocket != NULL)
    {
    closesocket(mySocket);
    mySocket = NULL;
    }
    if (fSockInitialized)
    {
    WSACleanup();
    fSockInitialized = false;
    }
    if(m_receiveThread)
    {
    WaitForSingleObject(m_receiveThread->m_hThread,2000);
    m_receiveThread = NULL;
    }
    }
    BOOL CUsbEngine::ListenNow()
    {

    // Bind the socket.
        sockaddr_in service;
    service.sin_family = AF_INET;
        service.sin_addr.s_addr = INADDR_ANY;
        service.sin_port = htons(27020);
       
    INT iRet = bind( mySocket, reinterpret_cast <SOCKADDR*> (&service), sizeof(service));
        if(SOCKET_ERROR ==iRet)
    {
    iRet = WSAGetLastError();
    hr = HRESULT_FROM_WIN32(iRet);
    return FALSE;
        }
       
        // Listen on the socket.
        iRet = listen(mySocket, 1);
    if (SOCKET_ERROR == iRet)
    {
    iRet = WSAGetLastError();
    hr = HRESULT_FROM_WIN32(iRet);
            return FALSE;
    }
    m_status = EConnected;
    m_receiveThread = AfxBeginThread(RevThread,(void *)this);
    return TRUE;
    }
    我在手机端是服务器SOCKET。第一次连接,PC客户端能顺利连接过来,但是重启之后,其他PC端再重启多少次,都无法连接到这里来。
    重启是这样的。
    对象:CUsbEngine *pEngine;
    if(pEngine)
    {
    delete pEngine;
    pEngine = NULL;
    }
    pEngine = new CUsbEngine();
    pEngine->ListenNow();
    发现第2次连接的时候,代码运行跟第一次一样。但PC端无论重启多少次,就是连不上。
    2009年12月5日 8:22