Netty实现简单服务端和客户端通信
服务端代码
/**
* @version 1.0.0
* @Description TODO
* @createTime 2022年04月03日 17:11:00
*/
public class NettyServer {
public static void main(String[] args) {
ServerBootstrap serverBootstrap = new ServerBootstrap();
NioEventLoopGroup boss = new NioEventLoopGroup();
NioEventLoopGroup worker = new NioEventLoopGroup();
serverBootstrap
.group(boss,worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel channel) throws Exception {
channel.pipeline().addLast(new StringDecoder());
channel.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
System.out.println(s);
}
});
}
})
.bind(8000);
}
}
客户端代码 :
/**
* @version 1.0.0
* @Description TODO
* @createTime 2022年04月03日 17:26:00
*/
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(20000);
}
}
}
依赖版本 :
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.7.Final</version>
</dependency>
现在netty最新版本到4.1.75,不过4.1.10以下版本支持JDK1.8, Netty的4.1.10以上的版本支持大于JDK9的版本,所以这块没有使用最新的版本.
另外一些涉及到IO的中间件或其它微服务组件也会用到Netty,下面看一下我的Demo依赖中 redis 中使用到了最新的Netty版本
从依赖中我们也可以看到底层通信确实有使用到netty,那么项目中有用到这些组件的话,其实不用再一次引入netty的依赖了
关于版本这个在启动后日志输出上我们也可以看出有提示jdk版本
关于netty的简单使用,及一些小问题就到这里了