Java Android套接字连接。错误的IP地址导致应用程序停止响应

时间:2011-12-09 17:01:50

标签: java android sockets

我有一个从Android手机到服务器的套接字连接,当我输入正确的IP地址和端口号时代码工作正常,但如果它们不正确,应用程序停止响应并告诉我强制退出。我假设 catch(UnknownHostException e)会捕获但是代码停止响应 socket = new Socket(_ip,_ portNum); 。 _ip和_port通过用户输入手机的内容传递给它。我需要这样做,如果有人输入错误的IP或端口,它不会崩溃,但告诉他们再次进入。

    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){
            }
    }
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

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

捕捉异常并对它们一无所知是一个非常糟糕的主意。

参考:(btw this is almost 10 years old...)

答案 1 :(得分:0)

套接字上的超时时间可能太长了。

尝试

Socket s = new Socket();

s.connect(sockaddr, 5000);

在catch语句中,如果失败,请关闭套接字等。