一般Netty內部封裝了JDK的NIO。java
使用Netty封裝NIO而不用NIO的緣由react
那麼經過代碼實現Netty。編程
實現Netty ,須要在pom.xml中加入依賴bootstrap
<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.6.Final</version> </dependency>
一、首先是服務端。其中實現了服務端的啓動,端口的綁定,接收新鏈接,打印數據服務器
public class NIOServer { public static void main(String[] args) throws IOException { Selector serverSelector = Selector.open(); Selector clientSelector = Selector.open(); new Thread(() -> { try { // 對應IO編程中服務端啓動 ServerSocketChannel listenerChannel = ServerSocketChannel.open(); listenerChannel.socket().bind(new InetSocketAddress(8000)); listenerChannel.configureBlocking(false); listenerChannel.register(serverSelector, SelectionKey.OP_ACCEPT); while (true) { // 監測是否有新的鏈接,這裏的1指的是阻塞的時間爲 1ms if (serverSelector.select(1) > 0) { Set<SelectionKey> set = serverSelector.selectedKeys(); Iterator<SelectionKey> keyIterator = set.iterator(); while (keyIterator.hasNext()) { SelectionKey key = keyIterator.next(); if (key.isAcceptable()) { try { // (1) 每來一個新鏈接,不須要建立一個線程,而是直接註冊到clientSelector SocketChannel clientChannel = ((ServerSocketChannel) key.channel()).accept(); clientChannel.configureBlocking(false); clientChannel.register(clientSelector, SelectionKey.OP_READ); } finally { keyIterator.remove(); } } } } } } catch (IOException ignored) { } }).start(); } }
server端中boss對應IOServer.java中建立新鏈接的部分,worker對應IOServer.java中的負責讀取數據的線程,主要用於讀取數據以及業務邏輯處理。網絡
二、而後是客戶端的實現併發
public class NettyClient { public static void main(String[] args) throws InterruptedException{ Bootstrap bootstrap = new Bootstrap(); NioEventLoopGroup group = new NioEventLoopGroup(); bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { channel.pipeline().addLast(new StringEncoder()); } }); Channel channel = bootstrap.connect("127.0.0.1",8000).channel(); while(true){ channel.writeAndFlush(new Date()+"Hello World"); Thread.sleep(2000); } } }
此段實現了,客戶端的鏈接框架