java中的readkey_写入通道后,Java Selector返回带有OP_READ的SelectionKey,而无需在无限循环中的数据...

我遇到了我的代码问题:我已经用Selector编写了简单的SocketChannel客户端,启动后它成功从服务器读取消息(服务器发送事件)。但是在写入套接字之后(请参阅main方法),选择器开始在infinyty循环中返回可读套接字,handleKey返回-1个字节,所以选择器所有时间返回OP_READ SelectionKey而没有数据用于读取。

对不起我的英语不好。

谢谢。

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.SocketChannel;

import java.util.Iterator;

public class SelectorTest

{

public SelectorTest() throws IOException {

selector = Selector.open();

}

private void runSelector() {

new Thread(new Runnable() {

public void run()

{

alive = true;

try {

while(alive) {

System.out.println("Selector started...");

selector.select();

Iterator keyIter = selector.selectedKeys().iterator();

while(keyIter.hasNext()) {

SelectionKey key = keyIter.next();

keyIter.remove();

handleKey(key);

}

}

} catch (IOException ex) {

ex.printStackTrace();

}

}

}).start();

}

private void handleKey(SelectionKey key) throws IOException {

SocketChannel chan = (SocketChannel) key.channel();

System.out.println("Processing selected...");

if(key.isConnectable()) {

System.out.println("Connecting ...");

if(chan.finishConnect()) {

key.interestOps(SelectionKey.OP_READ);

} else {

key.channel();

}

} else if(key.isReadable()) {

System.out.println("Processing reading...");

ByteBuffer buf = ByteBuffer.allocate(1024);

int readedBytes = chan.read(buf);

System.out.println("Readed: " + readedBytes);

buf.flip();

for(byte b : buf.array()) {

System.out.print((char) b);

}

} else if(key.isWritable()) {

System.out.println("Finishing writing...");

key.interestOps(SelectionKey.OP_READ);

}

}

public static void main(String[] args) throws IOException {

SocketChannel channel = SocketChannel.open();

channel.configureBlocking(false);

channel.connect(new InetSocketAddress("t1.sis.lan", 6001));

SelectorTest ds = new SelectorTest();

ds.runSelector();

channel.register(ds.selector, SelectionKey.OP_CONNECT);

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

for(;;) {

String line = in.readLine();

if(line==null) break;

if(line.toLowerCase().equals("bye")) break;

if (line.toLowerCase().equals("write")) {

String command = "GET_STREAMS\r\n\0";

ByteBuffer buf = ByteBuffer.allocate(1024);

buf.put(command.getBytes());

buf.flip();

channel.write(buf);

}

System.out.println("echo: "+line); // is it alive check

}

ds.alive = false;

ds.selector.wakeup();

channel.close();

}

private Selector selector;

private boolean alive;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值