Androidで2つのエミュレーター間にソケットチャネルを構築しようとしました。次のコードを書きました。
public SocketChannel connect2node(String ip, int port) {
SocketChannel client = null;
try {
client = SocketChannel.open(new InetSocketAddress(ip, port));
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
if (!client.isConnected()) {
Log.i("server connection", "error");
return null;
}
} catch (IOException e) {
String s = e.getMessage();
e.printStackTrace();
}
return client;
}
(ip、port)で別のエミュレーターを起動していないことに注意してください。つまり、接続は常に失敗します。上記のコードのデバッグを開始すると、
if (!client.isConnected()) {
次に、catch ブロックにジャンプします。
e.printStackTrace();
catch ブロック内の他のすべての行は実行されず、返されたときにクライアントは null ではありません。では、接続が正常に確立されたかどうかをどのように判断できますか?