public void initialize() throws IOException
{
boolean done = false;
try
{
Log.e(TAG,"SocketChannel.open:IP:["+hostIp+"Port:"+hostListenningPort+"].");
// 打开监听信道并设置为非阻塞模式
socketChannel = SocketChannel.open(new InetSocketAddress(hostIp,
hostListenningPort));
if (socketChannel != null)
{
socketChannel.socket().setTcpNoDelay(false);
socketChannel.socket().setKeepAlive(true);
// 设置 读socket的timeout时间
socketChannel.socket().setSoTimeout(
Const.SOCKET_READ_TIMOUT);
// 将选择器绑定到监听信道,只有非阻塞信道才可以注册选择器
socketChannel.configureBlocking(false);
// 打开并注册选择器到信道
Log.e(TAG,"ready to open selector success.");
selector = Selector.open();
if (selector != null)
{
Log.e(TAG,"open selector success.");
socketChannel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE|SelectionKey.OP_ACCEPT);
done = true;
}
}
} catch(Exception ex)
{
Log.e(TAG,"Create SocketChannel error msg:!"+ex.getMessage());
}
finally
{
Log.e(TAG,"Create SocketChannel catch error!");
if (!done && selector != null)
{
selector.close();
}
if (!done)
{
socketChannel.close();
}
}
}