Java NIO的簡單demo
最近學習了一下NIO的一些api,做了簡單的demo,感覺挺有意思的,有興許的可以一起學習
NIO的上手難度感覺還挺高的,學習曲線有一些,畢竟之前已經習慣了BIO的操作了,一下切過來過來還挺困難的,理清楚了基本的幾個概念就好理解多了,比如channel,buffer,selector,socketChannel,serverSocketChannel這幾個弄清楚基本就可以看得懂NIO的api了,不然連api都很困難弄明白。我是從極客學院看的基礎學習,然後寫的簡單的demo,只是demo而已,基礎學習可以看一下。
服務端程式碼
package org.chao.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
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.util.Iterator;
/**
* server 端
*
* @author xiezhengchao
* @since 2018/4/7 14:32
*/
public class ServerDemo{
private ByteBuffer readBuffer = ByteBuffer.allocateDirect(1024);
private ByteBuffer writeBuffer = ByteBuffer.allocateDirect(1024);
private Selector selector;
public ServerDemo() throws IOException{
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
ServerSocket serverSocket = serverSocketChannel.socket();
serverSocket.bind(new InetSocketAddress(8080));
System.out.println("listening on port 8080");
this.selector = Selector.open();;
// 繫結channel的accept
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public static void main(String[] args) throws Exception{
new ServerDemo().go();
}
private void go() throws Exception{
// block api
while(selector.select()>0){
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
iterator.remove();
// 新連線
if(selectionKey.isAcceptable()){
System.out.println("isAcceptable");
ServerSocketChannel server = (ServerSocketChannel)selectionKey.channel();
// 新註冊channel
SocketChannel socketChannel = server.accept();
if(socketChannel==null){
continue;
}
socketChannel.configureBlocking(false);
// 注意!這裡和阻塞io的區別非常大,在編碼層面之前的等待輸入已經變成了註冊事件,這樣我們就可以在等待的時候做別的事情,
// 比如監聽更多的socket連線,也就是之前說了一個執行緒監聽多個socket連線。這也是在編碼的時候最直觀的感受
socketChannel.register(selector, SelectionKey.OP_READ| SelectionKey.OP_WRITE);
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
buffer.put("hi new channel".getBytes());
buffer.flip();
socketChannel.write(buffer);
}
// 服務端關心的可讀,意味著有資料從client傳來了,根據不同的需要進行讀取,然後返回
if(selectionKey.isReadable()){
System.out.println("isReadable");
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
readBuffer.clear();
socketChannel.read(readBuffer);
readBuffer.flip();
String receiveData= Charset.forName("UTF-8").decode(readBuffer).toString();
System.out.println("receiveData:"+receiveData);
// 把讀到的資料繫結到key中
selectionKey.attach("server message echo:"+receiveData);
}
// 實際上服務端不在意這個,這個寫入應該是client端關心的,這只是個demo,順便試一下selectionKey的attach方法
if(selectionKey.isWritable()){
SocketChannel socketChannel = (SocketChannel)selectionKey.channel();
String message = (String) selectionKey.attachment();
if(message==null){
continue;
}
selectionKey.attach(null);
writeBuffer.clear();
writeBuffer.put(message.getBytes());
writeBuffer.flip();
while(writeBuffer.hasRemaining()){
socketChannel.write(writeBuffer);
}
}
}
}
}
}
客戶端程式碼
package org.chao.nio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
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.nio.charset.Charset;
import java.util.Iterator;
/**
* client 端
*
* @author xiezhengchao
* @since 2018/4/7 15:10
*/
public class ClientDemo{
private final ByteBuffer sendBuffer=ByteBuffer.allocate(1024);
private final ByteBuffer receiveBuffer=ByteBuffer.allocate(1024);
private Selector selector;
public ClientDemo()throws IOException{
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress(InetAddress.getLocalHost(),8080));
socketChannel.configureBlocking(false);
System.out.println("與伺服器的連線建立成功");
selector=Selector.open();
socketChannel.register(selector,SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
public static void main(String[] args) throws Exception{
final ClientDemo client=new ClientDemo();
Thread receiver=new Thread(client::receiveFromUser);
receiver.start();
client.talk();
}
private void talk()throws IOException {
while (selector.select() > 0 ){
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()){
SelectionKey key = it.next();
it.remove();
if (key.isReadable()) {
receive(key);
}
// 實際上只要註冊了關心寫操作,這個操作就一直被啟用
if (key.isWritable()) {
send(key);
}
}
}
}
private void send(SelectionKey key)throws IOException{
SocketChannel socketChannel=(SocketChannel)key.channel();
synchronized(sendBuffer){
sendBuffer.flip(); //設定寫
while(sendBuffer.hasRemaining()){
socketChannel.write(sendBuffer);
}
sendBuffer.compact();
}
}
private void receive(SelectionKey key)throws IOException{
SocketChannel socketChannel=(SocketChannel)key.channel();
socketChannel.read(receiveBuffer);
receiveBuffer.flip();
String receiveData=Charset.forName("UTF-8").decode(receiveBuffer).toString();
System.out.println("receive server message:"+receiveData);
receiveBuffer.clear();
}
private void receiveFromUser() {
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
try{
String msg;
while ((msg = bufferedReader.readLine()) != null){
synchronized(sendBuffer){
sendBuffer.put((msg+"\r\n").getBytes());
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
如果不啟用客戶端程式碼進行測試也可以用telnet命令進行測試telnet 127.0.0.1 8080
相關文章
- 初識NIO之Java小DemoJava
- 簡單的websocket demoWeb
- Java NIO原理及簡單拷貝實列Java
- 【譯】Java NIO 簡明教程系列之 NIO 簡介Java
- 【譯】Java NIO 簡明教程系列之 NIO 概述Java
- Java NIO 簡明教程系列Java
- 基於Java NIO 寫的一個簡單版 Netty 服務端JavaNetty服務端
- 人臉融合簡單demo
- 聊聊UDP、TCP和實現一個簡單的JAVA UDP小DemoUDPTCPJava
- SpringBoot切面Aop的demo簡單講解Spring Boot
- 簡單多播委託Demo
- 關於SSM框架的一個簡單DemoSSM框架
- 一個最簡單的WebSocket hello world demoWeb
- 關於dva框架的簡單操作以及demo框架
- 一個簡單的介面測試框架 demo框架
- 【譯】Java NIO 簡明教程系列之 ChannelJava
- Java NIOJava
- 深入的聊聊 Java NIOJava
- Java NIO Selector 的使用Java
- 使用 GPU 進行 Lightmap 烘焙 - 簡單 demoGPU
- springMVC簡單demo集合(持續更新中……)SpringMVC
- SignalR簡版web聊天室(demo簡單演示篇)SignalRWeb
- JavaScript ES6 async/await的簡單學習demoJavaScriptAI
- JAVA NIO BufferJava
- JAVA 探究NIOJava
- Java NIO SocketChannelJava
- Java NIO - BufferJava
- Java NIO - 群聊Java
- Java NIO:通道Java
- Java NIO filesJava
- Java NIO之Buffer的使用Java
- Java 簡單的rpc 一JavaRPC
- Java的簡單理解(2)Java
- Java NIO之SelectorJava
- Java NIO之BufferJava
- Java IO 和 NIOJava
- java NIO SocketClinet ServerSocketJavaServer
- Java NIO 概覽Java