0

I am Working on a client/server Broadcast Application using CSocket. While client connect to server OnAccept Method call. In OnAccept method I am creating a object of that class and Store that pointer of object in vector.

void ServerSocket::OnAccept(int nErrorCode)
{
    ServerSocket * User = new ServerSocket;
    temp->m_hSocket = INVALID_SOCKET;   
    Accept(*temp);  
    m_vConnectionObject.push_back(temp);
    CSocket::OnAccept(nErrorCode);
}

While Client close the connection my OnClose method will be called but when I am trying to access my vector in that method, it shows me that my vector is empty.

void ServerSocket::OnClose(int nErrorCode)
{       
    CString cname,name;
    UINT cport,port;

    GetPeerNameEx(cname,cport);

    int i=m_vConnectionObject.size();      //here i got "i= 0"

    std::vector<ServerSocket *>::iterator it = (m_vConnectionObject).begin() ;
    for ( ; it != m_vConnectionObject.end(); ++it)
    {   
        (*it)->GetPeerNameEx(name,port);
        if ((name==cname) && (port==cport))
        {
            //erase code
        }
    }

    CSocket::OnClose(nErrorCode);

}

I want to access that vector to delete the pointer of disconnected client.

PedFoot
  • 3
  • 4
  • Your iterator loop is wrong. When `erase(it)` returns, the iterator `it` is no longer valid, and you must not pre-increment it. Instead, use `while(it != m_vConnectionObject.end()) { ... if( ... ) it = m_vConnectionObject.erase(it); else ++it;`. – IInspectable Feb 18 '16 at 14:05

1 Answers1

0

You are performing OnAccept in the context of the server's listen socket, but you are performing OnClose in the context of the client's socket. So you're looking at two different vectors.

kfsone
  • 23,617
  • 2
  • 42
  • 74