一、 参考资料
参考尚硅谷netty教程
https://www.bilibili.com/video/BV1DJ411m7NR?p=7&vd_source=4cd1b6f268e2a29a11bea5d2568836ee
二、 Netty服务端
app.java
package com.sht.test;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* JAVA Netty
*
*/
public class App
{
public static void main( String[] args )
{
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workGroup = new NioEventLoopGroup();
try {
//创建服务器启动对象
ServerBootstrap bootStrap = new ServerBootstrap();
bootStrap
//设置两个线程组
.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
// TODO Auto-generated method stub
ch.pipeline().addLast(new NettyServerHandler());
}
});
//绑定㐰并且同步
ChannelFuture cf = bootStrap.bind(6666).sync();
//对关闭通道进行监听
cf.channel().closeFuture().sync();
}catch (Exception e) {
System.out.println("netty exception");
}finally {
//优雅关闭
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
NettyServerHandler.java
package com.sht.test;
import java.nio.ByteBuffer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
public class NettyServerHandler extends ChannelInboundHandlerAdapter{
private String reqStr;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//msg转ByteBuffer
ByteBuf buffer = (ByteBuf) msg;
reqStr = buffer.toString(CharsetUtil.UTF_8);
//"收到数据:" + buffer.toString()
System.out.println(String.format("收到[%s]数据:%s",
ctx.channel().remoteAddress(),
reqStr));//CharsetUtil.UTF_8
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//将接收到的数据返回客户端
ctx.writeAndFlush(Unpooled.copiedBuffer(reqStr,CharsetUtil.UTF_8));
}
}
三、 Netty客户端
NettyClient.java
package com.sht.test;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
public class NettyClient {
public static void main(String[] args) {
NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
try
{
Bootstrap bootStrap = new Bootstrap();
bootStrap
//设置两个线程组
.group(eventLoopGroup)
.channel(NioSocketChannel.class) //设置通道实现类
//.option(ChannelOption.SO_BACKLOG, 128)
//.childOption(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
// TODO Auto-generated method stub
ch.pipeline().addLast(new NettyClientHandler());
}
});
//绑定㐰并且同步
ChannelFuture cf = bootStrap.connect("127.0.0.1",6666).sync();
//对关闭通道进行监听
cf.channel().closeFuture().sync();
}catch (Exception e) {
System.out.println("netty exception");
}finally {
eventLoopGroup.shutdownGracefully();
}
}
}
NettyClientHandler.java
package com.sht.test;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
public class NettyClientHandler extends ChannelInboundHandlerAdapter{
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String reqStr = "hello";
ctx.writeAndFlush(Unpooled.copiedBuffer(reqStr,CharsetUtil.UTF_8));
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//msg转ByteBuffer
ByteBuf buffer = (ByteBuf) msg;
String respStr = buffer.toString(CharsetUtil.UTF_8);
//"收到数据:" + buffer.toString()
System.out.println(String.format("收到[%s]数据:%s",
ctx.channel().remoteAddress(),
respStr));//CharsetUtil.UTF_8
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
//两种关闭
//ctx.channel().close();
ctx.close();
}
}