客户端可以主动的给服务端发送消息,服务端收到消息之后将消息打印到控制台上,然后将消息返回复给客户端
public class NettyClient {
public static void main(String[] args) {
EventLoopGroup worker = new NioEventLoopGroup();
Bootstrap boot = new Bootstrap();// 客户端配置信息
boot.group(worker) // 绑定事件循环组
.channel(NioSocketChannel.class) // 设置channel类型
.handler(new ChannelInitializer<NioSocketChannel>() { // 添加处理器
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
nioSocketChannel.pipeline().addLast(new clientHandler()) // 给channel的pipeline上添加handler处理器
}
});
try {
// 获取建立连接的Channel通道,使用此通道主动发消息
Channel channel = boot.connect("127.0.0.1", 8989).sync().channel();
// 主动发送消息:
Scanner scan = new Scanner(System.in);
while (true) {
String message = scan.nextLine();
channel.writeAndFlush(Unpooled.copiedBuffer(message.getBytes()));
System.out.println(message);
if (message.equalsIgnoreCase("exit")) {
break;
}
}
channel.closeFuture().sync(); // 关闭
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
worker.shutdownGracefully();
}
}
}
//回调函数类
class clientHandler extends ChannelInboundHandlerAdapter {
// 只有当建立连接后执行一次
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("连接建立....);
}
// 有读事件发生时执行
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("reading message...");
ByteBuf readBuf = (ByteBuf) msg;
System.out.println(readBuf.toString(CharsetUtil.UTF_8));
}
//有异常时执行
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("throw");
cause.printStackTrace();
ctx.close();
}
}
服务端
public class NettyServer {
public static void main(String[] args) {
// 创建两个循环事件组
EventLoopGroup boss = new NioEventLoopGroup(); // 处理接收
EventLoopGroup worker = new NioEventLoopGroup(); // 处理接收之后的操作
ServerBootstrap boot = new ServerBootstrap(); // 创建配置信息类
boot.group(boss,worker )
.channel(NioServerSocketChannel.class) // 通过反射的手段,创建这个类的实例
.childHandler(new ChannelInitializer<NioSocketChannel>() {
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
nioSocketChannel.pipeline().addLast(new serverHandler()) //添加自定义handler
}
});
try {
ChannelFuture future = boot.bind(8989).sync(); // 绑定端口开始监听
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
System.out.println("222");
e.printStackTrace();
}finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
//服务端回调函数
class serverHandler extends ChannelInboundHandlerAdapter {
//有读事件发生时调用
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("333");
System.out.println(">>>>>:"+msg);
ByteBuf buf = (ByteBuf) msg;
//打印收到的信息
System.out.println(buf.toString(CharsetUtil.UTF_8));
// 将收到的信息返回
ctx.writeAndFlush(buf);
}
// 连接建立时调用
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
//ctx.fireChannelInactive();
// 连接断开时调用
System.out.println(ctx.channel().remoteAddress()+":上线");
}
// 连接断开时调用
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress()+":下线");
}
/**
* @Description: 异常处理
* @Param: ctx 当前这个handler逻辑结束之后返回的对象
* @return: void
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}