一般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); } } }
此段实现了,客户端的链接框架