我正在为 Android 4.03 开发一个应用程序。相关代码是这样的:
public void startConnection() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i(LOG_TAG, "Beginning");
_socket = new Socket(_server, _port);
_socket.setSoTimeout(DEFAULT_SOCKET_TIMEOUT);
_writer = new BufferedWriter(new OutputStreamWriter(_socket.getOutputStream()));
_reader = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
_in = new InputThread(_reader, new InputThreadObserver());
_in.start();
Log.i(LOG_TAG, "End");
} catch (UnknownHostException e) {
Log.i(LOG_TAG, "UnknownHostException");
} catch (IOException e) {
Log.i(LOG_TAG, "IOException");
}
}
}).start();
}
套接字的创建在一个新线程中执行,否则执行会冻结几秒钟。
如果我将变量设置_server
为现有主机(例如www.google.com
),一切都会好起来的。但是,如果我将_server
变量设置为不存在的主机(例如asd.asd
),我真的希望在记录器中打印“UnknownHostException”。这不会发生(但_socket
变量是null
)。它只打印“开始”(而不是“结束”)。任何的想法?
编辑:
变量声明如下:
private String _server;
private Socket _socket;
private int _port;
private BufferedWriter _writer;
private BufferedReader _reader;
private InputThread _in;
编辑:
我正在尝试这个:
public void startConnection() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i(LOG_TAG, "Beginning");
_socket = new Socket(_server, _port);
if (_socket == null)
Log.i(LOG_TAG, "NULL SOCKET! (test 1)");
} catch (Exception e) {
Log.i(LOG_TAG, "EXCEPTION!");
}
if (_socket == null)
Log.i(LOG_TAG, "NULL SOCKET! (test 2)");
}
}).start();
}
不知道为什么,但输出只是:
Beginning
编辑:
经过 3 分 13 秒的等待,我终于得到:
EXCEPTION!
NULL SOCKET! (test 2)
这正常吗?不应该立即抛出 UnknownHostException 吗?