我正在为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吗?
答案 0 :(得分:0)
查看API docs,如果_server是一个字符串,那么你将获得一个UnknownHost异常。如果它是任何其他可能性,你就不会。 特别是此签名将创建例外:
Socket(String host,
int port)
throws UnknownHostException,
IOException