简体   繁体   中英

Java Android Socket Connection. Wrong ip address causing application to stop responding

I have a socket connection from an android phone to a server and the code works fine when i enter the correct IP address and port number but if they are incorrect the application stops responding and tells me to force quit. I would assume that the catch(UnknownHostException e) would catch that but the code stops responding at socket = new Socket(_ip, _portNum); . _ip and _port are passed into it by what the user enters into the phone. i need to make it so if someone enters the wrong IP or Port it wont crash but tell them to enter again.

    public void Connect(String _ip, int _portNum) throws ParserConfigurationException, SAXException, IOException{  

    //CREATES SOCKET
    Socket socket = null;
    DataInputStream input = null;
    DataOutputStream output = null; 
    //CREATE DATA STREAMS   
    try{
        Log.e("trying to connect","trying to connect"); //sends to log
        socket = new Socket(_ip, _portNum); //stops responding here.
        Log.i("Socket Connected", "Socket Connected"); //not sent to log

        output = new DataOutputStream(socket.getOutputStream());
        input = new DataInputStream(socket.getInputStream());       

        }catch(UnknownHostException e){
        }catch(IOException e){
        }

        //IF STREAMS ARE OPEN SEND MESSAGES
    if (socket != null && output != null && input != null){          
        try{

            //MESSAGES FOR TESTING          
            output.writeBytes("HELLO2 \n");             

            String response;
            while((response = input.readLine()) != null){
                System.out.println("Server: " + response);                  

                //MESSAGE FOR TESTING
                output.writeBytes("Test \n");

                TextView test = (TextView) findViewById(R.id.TestText);
                // display text returned from server
                test.setText(response);            
            }   

            //CLOSE STREAMS AND CONNECTION          
            output.close();
            input.close();      
            socket.close(); 
                Log.i("Connections closed", "Connections closed");
            }catch(UnknownHostException e){
            }catch(IOException e){
            }
    }
}

Any assistance is greatly apprectiated.

        }catch(UnknownHostException e){
    }catch(IOException e){
    }

Its a really really bad idea to catch exceptions and do nothing about them.

Reference: (btw this is almost 10 years old...)

Maybe the timeout is too long on the socket.

Try

Socket s = new Socket();

s.connect(sockaddr, 5000);

Inside the catch statement, if it fails, close the socket etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM