【发布时间】:2012-01-16 22:53:09
【问题描述】:
我有一个从安卓手机到服务器的套接字连接,当我输入正确的 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){
}
}
}
非常感谢任何帮助。
【问题讨论】: