我希望该程序在我输入内容时给我一个回音,我没有收到任何错误但它没有工作,它连接正常但我没有收到任何回复我输入服务器
private static Selector selector;
public static void main(String[] args) throws IOException {
selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.bind(new InetSocketAddress("localhost", 8080));
ssc.configureBlocking(false);
ssc.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext();) {
SelectionKey key = it.next();
it.remove();
if (key.isAcceptable())
acceptRead(key);
else if (key.isWritable())
write(key);
}
}
}
private static void acceptRead(SelectionKey key) throws IOException {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
System.out.println("Connected with " + sc);
sc.configureBlocking(false);
SelectionKey key2 = sc.register(selector, SelectionKey.OP_WRITE);
ByteBuffer buf = ByteBuffer.allocate(32);
sc.read(buf);
buf.flip();
key2.attach(buf);
}
private static void write(SelectionKey key) throws IOException {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buf = (ByteBuffer) key.attachment();
sc.write(buf);
}
}
答案 0 :(得分:0)
这里的代码很奇怪。
accept()
。read()
。read()
获得-1,则必须关闭该频道。compact()
缓冲区,你肯定想再次为OP_READ
注册频道吗?