-
Notifications
You must be signed in to change notification settings - Fork 0
NIO例子
public class AppTest {
- public static void main(String[] args) {
- try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); Selector selector = Selector.open();
serverSocketChannel.configureBlocking(false); InetSocketAddress address = new InetSocketAddress("192.168.111.132", 8090); serverSocketChannel.bind(address); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
- System.out.println("server is running");
- while(true) {
int key = selector.select(); if(key != 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); while(iterator.hasNext()) {
SelectionKey selectionKey = iterator.next(); iterator.remove(); if(selectionKey.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel(); SocketChannel socketChannel = ssc.accept(); if(socketChannel != null) {
socketChannel.configureBlocking(false);
socketChannel.register(selectionKey.selector(), SelectionKey.OP_READ); System.out.println(socketChannel.socket());
}
- }else if(selectionKey.isReadable()){
- SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int readBytes = socketChannel.read(readBuffer); if(readBytes > 0) {
readBuffer.flip(); byte [] bytes = new byte[readBuffer.remaining()];
readBuffer.get(bytes); String body = new String(bytes,"UTF-8");System.out.println("from-client["+socketChannel+"] : " + body);
//resposne String responseStr = "Hello,boy"; byte [ ] response = responseStr.getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(response.length); writeBuffer.put(response); writeBuffer.flip();socketChannel.write(writeBuffer);
- }else if(readBytes < 0){
- selectionKey.cancel(); socketChannel.close();
- }
- }
}
- }else {
- System.out.println("key = 0");
}
}
- } catch (Exception e) {
- e.printStackTrace();
}
}
}