0

In my server located in a android device , if the number number of clients exceeds a specific number then the server close the socket. But in my client(other android device) i get a force close. How can i handle it gracefully? Here is the connect part on my client:

    serverIpAddress = serverIp.getText().toString();

    if (!serverIpAddress.equals(""))
    {
            try
            {
                 InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                 SocketAddress sockaddr = new InetSocketAddress(serverAddr, 5000);
                 nsocket = new Socket();
                 nsocket.connect(sockaddr);                    
            }catch(Exception e){
                 Log.i("Connect", "Connection Error");
            }

            if (nsocket.isConnected()){
                  score.setText("Your score is " + sc);
                  serverIp.setVisibility(View.GONE);
                  connectPhones.setVisibility(View.GONE);
                  enterIP.setVisibility(View.GONE);
                  Log.i("Connect", "Socket created, streams assigned");
                  Log.i("Connect", "Waiting for inital data..." + nsocket.isConnected());
                  receiveMsg();
            }
Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
dothedos
  • 169
  • 5
  • 20
  • Add a close procedure to the protocol you're using over the socket. It's hard for us to help you do that since we don't know what your protocol is. Perhaps the server could send the client a "try again later" message and then the client would close the socket? That way, the server only closes if the client doesn't respond and normally it happens cleanly. – David Schwartz May 29 '12 at 18:55
  • Also catching `Exception` [is considered usually a bad practice](http://stackoverflow.com/questions/4716353/if-catching-null-pointer-exception-is-not-a-good-practice-is-catching-exception) – m0skit0 May 29 '12 at 19:15

2 Answers2

0

Keep checking the socket connection is still open or not using isClosed() within an infinite loop, when server closes its connection, the isClosed() gets true, and then display a message or toast giving your desired reason to the user.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
0

Sounds like whatever you are using to read the socket is a blocking read, and throws an exception when the socket closes and it is stuck at that read. Make sure that read is in a try block, and use the catch/finally to gracefully exit whatever you are doing at that moment.

Drake Clarris
  • 1,047
  • 6
  • 10