Skip to content

Instantly share code, notes, and snippets.

@fuyuntt
Created April 16, 2017 18:12
Show Gist options
  • Save fuyuntt/2a34cf564fcc2ed7a449125d98835836 to your computer and use it in GitHub Desktop.
Save fuyuntt/2a34cf564fcc2ed7a449125d98835836 to your computer and use it in GitHub Desktop.
java nio test
package com.fuyun.scala;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Set;
/**
* Created by fuyun on 2017/4/17.
* nio test
*/
public class NioTest {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(1234));
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder();
while (true) {
int selected = selector.select();
if (selected <= 0) {
continue;
}
Set<SelectionKey> selectionKeys = selector.selectedKeys();
for (SelectionKey selectionKey : selectionKeys) {
if (selectionKey.isAcceptable()) {
SocketChannel socketChannel = ((ServerSocketChannel) selectionKey.channel()).accept();
socketChannel.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(10);
socketChannel.register(selector, SelectionKey.OP_READ, buffer);
} else if (selectionKey.isReadable()) {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
StringBuilder sb = new StringBuilder();
while (socketChannel.read(buffer) >= 1) {
buffer.flip();
sb.append(utf8Decoder.decode(buffer));
buffer.clear();
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
sb.reverse();
sb.append("\n");
CharBuffer charBuffer = CharBuffer.wrap(sb);
ByteBuffer writeBuffer = utf8Encoder.encode(charBuffer);
socketChannel.write(writeBuffer);
}
}
selectionKeys.clear();
}
}
}
@fuyuntt
Copy link
Author

fuyuntt commented Apr 16, 2017

使用nio实现非阻塞服务器

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment