SocketChannel
クライアント側のサーバーからTCPストリームを受信するために使用します。例えば:
Selector selector=Selector.open();
SocketChannel mychannel=SocketChannel.open(new InetSocketAddress(ip,port));
channel.configureBlocking(false);
SelectionKey channelkey=channel.register(selector,SelectionKey.OP_READ);
次に、このselector.select()
メソッドを使用して読み取りの問題を処理できます。
while(true){
if(selector.select()!=0){
Iterator<SelectionKey> it=selector.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey key=it.next();
it.remove();
if(key.isReadable()){
if(key.equals(channelkey)){
//concrete handle
...
}
}
}
}
}
具体的なハンドルで、サーバー側からtcpストリームを受信するためにInputStream(ストリームラインを読みたい)を使用したいことを考えると、2つの方法があります.1つは使用する方法channel.socket()
、もう1つはチャネルを使用する方法です。ここではchannel.socket()
、たとえば、を使用します。
SocketChannel channel = (SocketChannel) key.channel();
key.cancel();
channel.configureBlocking(true);
InputStream ins = Channels.newInputStream(channel);
InputStreamReader is = new InputStreamReader(ins,"utf-8");
BufferedReader in = new BufferedReader(is);
String res = in.readLine();
while (!res.equals("")) {
System.out.println(res);
res = in.readLine();
}
......①
OK、これでtcpストリームの読み取りが1回終了しました。セレクターを引き続き使用するには、チャネルブロックモードをfalseに設定する必要があります。
channel.configureBlocking(false);
問題は、チャンネルとセレクターを組み合わせたキーがキャンセルされたということです。チャンネルを再度登録したいのですが、どうすればよいですか?①で再度使用するmychannel.register(selector, SelectionKey.OP_READ)
とスローするようException
です。
私のrun()メソッドコードは次のとおりです。
try {
if (selector.select(getTimeout()) != 0) {
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
if (key.isReadable()) {
SocketChannel channel = (SocketChannel) key.channel();
key.cancel();
channel.configureBlocking(true);
InputStream ins = Channels.newInputStream(channel);
InputStreamReader is = new InputStreamReader(ins,"utf-8");
BufferedReader in = new BufferedReader(is);
String res = in.readLine();
while (!res.equals("")) {
System.out.println("========" + res);
res = in.readLine();
}
channel.configureBlocking(false);
System.out.println(key.isValid());
proxykey=channel.register(selector, SelectionKey.OP_READ);
}
it.remove();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
スローされる例外は次のとおりです。
Exception in thread "Thread-0" java.nio.channels.CancelledKeyException
at sun.nio.ch.SelectionKeyImpl.ensureValid(Unknown Source)
at sun.nio.ch.SelectionKeyImpl.interestOps(Unknown Source)
at java.nio.channels.spi.AbstractSelectableChannel.register(Unknown Source)
at java.nio.channels.SelectableChannel.register(Unknown Source)
at AgentThread.run(AgentThread.java:185)