0

So i have this application in which I am storing Sockets in an ArrayList on the Server side. When the client closes its application the socket must close as well but It doesnt reflect the changes in the ArrayList in the server.

class arrays
{
    public static ArrayList<Socket> online_buyer=new ArrayList<Socket>(); 
    public static ArrayList<Socket> online_seller=new ArrayList<Socket>(); 
        public static ArrayList<String> buyer_prod=new ArrayList<String>();

}

    public void seller_display()
    {
        while(true)
        {   


            if(flag==1)
            {

                synchronized(sock)
                {
                for(int i=0;i<arrays.online_buyer.size();i++)
                {
                System.out.println(arrays.buyer_prod.get(i));
                }
                flag=0;
                }
            }


            check2();

        }

    }


    public void check2()
    {
        for(int i=0;i<arrays.online_buyer.size();i++)
        {
            try 
            {
            Thread.sleep(1000);
            } 
            catch (InterruptedException e) 
            {
            e.printStackTrace();
            }
            **while(!arrays.online_buyer.get(i).isConnected())** 
            {
                arrays.online_buyer.remove(i);
                arrays.buyer_user.remove(i);
                arrays.buyer_add.remove(i);
                arrays.buyer_prod.remove(i);
                arrays.time.remove(i);
                arrays.buyer_no.remove(i);
                flag=1;
                System.out.println("RECORD DELETED");
            }


        }

    }


public void run()
    {
    get_details();

    }
}

Now the statement while(!arrays.online_buyer.get(i).isConnected()) must be while(!false)=true. When i close the socket from the client side as isconnected()method must return false. But this statement never runs to be false even if i close the socket from client.

1 Answers1

1

When I close the socket from the client side as isConnected() method must return false.

No it mustn't. Where does it say that?

The reality of this is that isConnected() returns true if you have ever connected this Socket, which you have. The correct way to detect peer termination is as follows:

  • read() returns -1
  • readLine() returns null
  • readXXX() throws EOFException for any other XXX
  • write() throws IOException
user207421
  • 305,947
  • 44
  • 307
  • 483
  • Thanks man. They should have named the method was everconnected – Kartik Gupta Jun 04 '14 at 10:45
  • 'Returns the connection state *of the socket*' is clear enough, but I would agree they should have added warnings about *not of the connection* to both this and `isClosed().` – user207421 Jun 04 '14 at 10:55