《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
======================================================================================
Netty服务器在6666端口监听,客户端发送消息给服务器 “Hello,服务器”
服务器可以回复消息给客户端 “hello 客户端”
NettyServer
服务器,监听6666端口
package com.wanshi.netty.simple;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyServer {
public static void main(String[] args) throws Exception {
// 创建BossGroup 和 WorkerGroup
//说明
//1.创建2个线程组,分别是boosGroup和workerGroup
//2.boosGroup只是处理连接请求,真正的与客户端业务处理,会交给workerGroup完成
//3.两个都是无限循环
//4. boosGroup 和 workerGroup 含有的子线程(NioEventLoop)的个数
// 默认实际 CPU核数*2
EventLoopGroup boosGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//创建服务器端的启动的对象,配置参数
ServerBootstrap bootstrap = new ServerBootstrap();
//使用链式编程来进行设置
bootstrap.group(boosGroup, workerGroup) // 设置两个线程组
.channel(NioServerSocketChannel.class) //使用NioServerSocketChannel作为服务器的通道实现
.option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列等待连接个数
.childOption(ChannelOption.SO_KEEPALIVE, true) // 设置保持活动连接状态
.childHandler(new ChannelInitializer() { // 创建一个通道初始化对象(匿名对象)
//给pipeline 设置处理器
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//可以使用一个集合管理SocketChannel,再推送消息时,可以将业务加入到各个channel对应的NioEventLoop的taskQueue
//或者 scheduleTaskQueue
System.out.println(“客户 SocketChannel:” + socketChannel.hashCode());
socketChannel.pipeline().addLast(new NettyServerHandler());
}
}); //给我们的workerGroup的某一个EventLoop的对应的管道设置处理器
System.out.println(“服务器 is ready…”);
//绑定一个端口并且同步,生成了一个ChannelFuture对象
//启动服务器并绑定端口
ChannelFuture channelFuture = bootstrap.bind(6668).sync();
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (channelFuture.isSuccess()) {
System.out.println(“监听端口 6668 成功”);
} else {
System.out.println(“监听端口 6668 失败”);
}
}
});
//对关闭通道进行监听
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
//优雅关闭
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
NettyServerHandler
服务器处理器,处理客户端发送的消息并输出到控制台,并向服务端发送消息
package com.wanshi.netty.simple;
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;
import java.util.concurrent.TimeUnit;
/**
-
自定义一个Handler,需要继承netty规定好的某个HandlerAdapter
-
这时我们自定义的handler才能称为一个handler
*/
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
//读取数据事件(这里我们可以读取客户端发送的消息)
/**
-
1.ChannelHandlerContext ctx: 上下文对象,含有 管道pipeline,通道channel,地址
-
2.Object msg:就是客户端发送的数据,默认Object
-
@param ctx
-
@param msg
-
@throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(“server ctx =” + ctx);
//将 msg 转成一个ByteBuf
// ByteBuf buf = (ByteBuf) msg;
// System.out.println(“客户端发送消息是:” + buf.toString(CharsetUtil.UTF_8));
// System.out.println(“客户端地址:” + ctx.channel().remoteAddress());
//自定义普通任务队列,将耗时长的任务加入队列,定义到NioEventLoop --> taskQueue
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(10 * 1000);
ctx.writeAndFlush(Unpooled.copiedBuffer(“hello,客户端:喵2~”, CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
ctx.channel().eventLoop().execute(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(20 * 1000);
ctx.writeAndFlush(Unpooled.copiedBuffer(“hello,客户端:喵3~”, CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//用户自定义定时任务 --》 该任务是提交到 scheduleQueue中
ctx.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(5 * 1000);
ctx.writeAndFlush(Unpooled.copiedBuffer(“hello,客户端:喵4~”, CharsetUtil.UTF_8));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, 5, TimeUnit.SECONDS);
System.out.println(“go ~”);
}
/**
-
数据读取完毕
-
@param ctx
-
@throws Exception
*/
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//writeAndFlush 是 write+flush
//将数据写入到缓存,并刷新
//一般讲,需要对发送的数据进行编码
ctx.writeAndFlush(Unpooled.copiedBuffer(“hello,客户端:喵1~”, CharsetUtil.UTF_8));
}
//处理异常,一般是需要关闭通道
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
NettyClient
客户端,用于连接服务器
package com.wanshi.netty.simple;
import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
public class NettyClient {
public static void main(String[] args) throws Exception {
//客户端需要一个事件循环组
EventLoopGroup eventExecutors = new NioEventLoopGroup();
try {
//创建一个客户端启动对象
//客户端使用的不是ServerGroup 而是Bootstrap
Bootstrap bootstrap = new Bootstrap();
//设置相关参数
bootstrap.group(eventExecutors) //设置线程组
.channel(NioSocketChannel.class) //设置客户端通道的实现类(反射)
.handler(new ChannelInitializer() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new NettyClientHandler()); //加入自己的处理器
}
});
System.out.println(“客户端 is ok…”);
//启动客户端去连接服务器端, netty异步模型ChannelFuture
ChannelFuture channelFuture = bootstrap.connect(“127.0.0.1”, 6668).sync();
//给关闭通道进行监听
channelFuture.channel().closeFuture().sync();
} finally {
//优雅关闭线程池
eventExecutors.shutdownGracefully();
}
}
}
NettyClientHandler
客户端处理器,处理服务器发送的消息输出到控制台,并向服务器发送消息
package com.wanshi.netty.simple;
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 {
/**
-
当通道就绪就会触发该方法
-
@param ctx
-
@throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("client " + ctx);
ctx.writeAndFlush(Unpooled.copiedBuffer(“hello,服务端Server:喵~”, CharsetUtil.UTF_8));
}
/**
-
当通道有读取事件时,会触发
-
@param ctx
-
@param msg
-
@throws Exception
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//将msg转成buf
ByteBuf buf = (ByteBuf) msg;
System.out.println(“服务器回复的消息:” + buf.toString(CharsetUtil.UTF_8));
System.out.println(“服务器的地址:” + ctx.channel().remoteAddress());
}
// 当通道发生异常时执行此方法
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
Java高频面试专题合集解析:
当然在这还有更多整理总结的Java进阶学习笔记和面试题未展示,其中囊括了Dubbo、Redis、Netty、zookeeper、Spring cloud、分布式、高并发等架构资料和完整的Java架构学习进阶导图!
更多Java架构进阶资料展示
《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!
ht(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
Java高频面试专题合集解析:
[外链图片转存中…(img-bmeUdkq0-1714734596443)]
当然在这还有更多整理总结的Java进阶学习笔记和面试题未展示,其中囊括了Dubbo、Redis、Netty、zookeeper、Spring cloud、分布式、高并发等架构资料和完整的Java架构学习进阶导图!
[外链图片转存中…(img-J6zgJjkw-1714734596444)]
更多Java架构进阶资料展示
[外链图片转存中…(img-5UWLuxyE-1714734596444)]
[外链图片转存中…(img-udlQB8Hx-1714734596444)]
[外链图片转存中…(img-VzxPvdd4-1714734596445)]
《一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频+实战项目源码》,点击传送门,即可获取!