其实看netty看了好久了,关于IO/NIO还有也看了好久了,从刚开的一脸懵逼到现在已经大致熟悉netty开发,满满的辛酸。这次先就给出个demo,能在项目中运行起来,关于netty的详细介绍,等以后学习后再继续更新。
此demo实现的效果是,先运行服务端进行监听。然后运行客户端,客户端与服务端建立连接后,会向服务端发送消息:I am client ...,然后服务端会向客户端发送:hi , Im is server...
maven引用:
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.14.Final</version>
</dependency>
创建服务端:
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.TimeUnit;
/**
* Created by XiChuan on 2018-11-05.
*/
public class Server {
private int port;
public Server(int port){this.port = port;}
public void run()throws Exception{
EventLoopGroup bossGroup = new NioEventLoopGroup(); //用来接收进来的连接
EventLoopGroup workerGroup = new NioEventLoopGroup(); //用来处理已经被接收的连接
try {
ServerBootstrap bootstrap = new ServerBootstrap(); //启动NIO服务的辅助启动类
bootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class) //服务端
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) t