一、需求
建立netty通讯并通过编写客户端的方式发送消息和响应消息。
二、环境
idea 2018
JDK1.8
maven 3.3.1
Netty 5.0.0.Alpha2
三、代码实现
1、实现server端的ServerHandler
创建一个ServerHandler 继承 Netty的ChannelInboundHandlerAdapter 类。并重写方法 [idea快捷键 Ctrl+o]
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.util.CharsetUtil;
@Sharable //表明一个ChannelHandler可以被多个Channel安全的共享
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//每次收到消息时被调用
ByteBuf in = (ByteBuf) msg;
System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8)); //把消息打印到控制台
ctx.write(in); //将收到的消息写入发送方,不刷新输出消息
}
@Override //用来通知handler上一个ChannelRead()是被这批消息中的最后一个消息调用
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//刷新挂起的数据到远端,然后关闭Channel
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
@Override //在读操作异常被抛出时被调用
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace(); //打印异常堆栈跟踪消息
ctx.close(); //关闭这个Channel
}
}
2、实现服务端server
import com.ygq.handler.EchoServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 java.net.InetSocketAddress;
/**
* 服务端
*/
public class EchoServer {
private final int port;
public EchoServer(int port) {
this.port = port;
}
public void start() throws Exception {
final EchoServerHandler serverHandler = new EchoServerHandler();
EventLoopGroup group = new NioEventLoopGroup(); //创建EventLoopGroup
try {
ServerBootstrap b = new ServerBootstrap(); //创建ServerBootstrap
b.group(group)
.channel(NioServerSocketChannel.class) //指定使用一个NIO传输Channel
.localAddress(new InetSocketAddress(port)) //用指定的端口设置socket地址
.childHandler(new ChannelInitializer<SocketChannel>() { //在Channel的ChannelPipeline中加入EchoServerHandler
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(serverHandler);//EchoServerHandler是@Sharable的,所以我们可以一直用同一个实例
}
});
ChannelFuture f = b.bind().sync();//异步的绑定服务器,sync()一直等到绑定完成
f.channel().closeFuture().sync();//获得这个Channel的CloseFuture,阻塞当前线程直到关闭操作完成
} finally {
group.shutdownGracefully().sync();//关闭EventLoopGroup,释放所有资源
}
}
public static void main(String args[]) throws Exception {
new EchoServer(8080).start();
}
}
3、实现client端的Handler
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
@Sharable //标记这个类的实例可以被多个Channel共享
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
@Override //和服务器的连接建立起来后被调用
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//当收到连接成功的通知,发送一条消息
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
}
// @Override //从服务器收到一条消息时被调用
// protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
// System.out.println("Client received: " + msg.toString(CharsetUtil.UTF_8));//打印收到的消息到日志
// }
@Override //处理过程中异常发生时被调用
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();//异常发生时,记录错误日志,关闭Channel
ctx.close();
}
protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
System.out.println("收到的消息了....."+byteBuf.toString(CharsetUtil.UTF_8));
}
}
四、实现client端
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
@Sharable //标记这个类的实例可以被多个Channel共享
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf>{
@Override //和服务器的连接建立起来后被调用
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//当收到连接成功的通知,发送一条消息
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
}
@Override //处理过程中异常发生时被调用
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();//异常发生时,记录错误日志,关闭Channel
ctx.close();
}
protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
System.out.println("收到的消息了....."+byteBuf.toString(CharsetUtil.UTF_8));
}
}