一、群聊系统
要求:编写一个 Netty 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞);实现多人群聊。服务器端可以监测用户上线、离线,并实现消息转发功能;客户端通过 channel 可以无阻塞发送消息给其它所有用户,同时可以接收其它用户发送的消息(由服务器转发得到)。
服务端:
public class GroupChatServer {
// 监听端口
private int port;
public GroupChatServer(int port) {
this.port = port;
}
public static void main(String[] args) throws Exception {
new GroupChatServer(7000).run();
}
/**
* 处理客户端的请求
*
* @throws Exception
*/
public void run() throws Exception {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();// 默认 8 个NioEventLoop
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// 向 pipeline 加入解码器
pipeline.addLast("decoder", new StringDecoder());
// 向 pipeline 加入编码器
pipeline.addLast("encoder", new StringEncoder());
// 向 pipeline 加入自己的业务处理handler
pipeline.addLast(new GroupChatServerHandler());
}
});
System.out.println("netty 服务器启动");
ChannelFuture channelFuture = b.bind(port).sync();
// 监听关闭
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {
// public static List<Channel> channels = new ArrayList<Channel>();
// 使用一个Map管理channel
// public static Map<String,Channel> channels = new HashMap<String,Channel>();
// 定义一个channel组,管理所有的channel,GlobalEventExecutor.INSTANCE 是全局的事件执行器,是一个单例
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/**
* handlerAdded 表示连接建立,一旦连接,第一个被执行
*
* @param ctx
* @throws Exception
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
// 新用户加入群聊,向channelGroup中的其他所有用户发送消息,不需要我们自己遍历channelGroup,类似于广播
channelGroup.writeAndFlush("客户端[" + channel.remoteAddress() + "]加入聊天," + sdf.format(new Date()) + "\n");
// 将当前channel加入到channelGroup
channelGroup.add(channel);
System.out.println("当前在线人数:" + channelGroup.size());
}
/**
* 断开连接:离线
*
* @param ctx
* @throws Exception
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
// 向其他在线客户端发送消息通知
channelGroup.writeAndFlush("客户端[" + channel.remoteAddress() + "]离线了");
System.out.println("当前在线人数:" + channelGroup.size());
}
/**
* channel 处于活动状态
*
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + " 处于活跃状态");
}
/**
* channel 处于不活跃状态
*
* @param ctx
* @throws Exception
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress() + " 处于不活跃状态,可能离线了");
}
/**
* 一旦有可读取数据时触发
*
* @param ctx
* @param msg
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
// 获取当前channel
Channel channel = ctx.channel();
// 遍历channelGroup,根据不同情况发送不同消息
channelGroup.forEach(ch -> {
if (channel != ch) {
// 向其他客户端转发消息
ch.writeAndFlush("客户端[" + channel.remoteAddress() + "]说:" + msg + "\n");
} else {
ch.writeAndFlush("[自己]说:" + msg + "\n");
}
});
// 踢出出群
//channelGroup.remove(channel);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
}
客户端:
public class GroupChatClient {
private final String host;
private final int port;
public GroupChatClient(String host, int port) {
this.host = host;
this.port = port;
}
public static void main(String[] args) throws Exception {
new GroupChatClient("127.0.0.1", 7000).run();
}
public void run() throws Exception {
NioEventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
pipeline.addLast(new GroupChatClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
Channel channel = channelFuture.channel();
System.out.println("---" + channel.localAddress() + "---");
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String msg = scanner.nextLine();
channel.writeAndFlush(msg + "\n");
}
} finally {
group.shutdownGracefully();
}
}
}
class GroupChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg.trim());
}
}
当服务端和客户端以 String 类型的数据进行数据交互时,可以使用 netty 提供的 String 类型的编码器和节码器。
二、心跳检测
编写一个 Netty 心跳检测机制案例, 当服务器超过3秒没有读时,就提示读空闲;当服务器超过5秒没有写操作时,就提示写空闲;当服务器超过7秒没有读或者写操作时,就提示读写空闲。
public class NettyIdleServer {
public static void main(String[] args) throws Exception {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup);
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new IdleStateHandler(3, 5, 2, TimeUnit.SECONDS));
// 加入一个进一步处理 IdleStateEvent 的自定义handler
pipeline.addLast(new NettyIdleHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
class NettyIdleHandler extends ChannelInboundHandlerAdapter {
/**
* @param ctx
* @param evt : 事件
* @throws Exception
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
String eventType = null;
switch (event.state()) {
case READER_IDLE:
eventType = "读空闲";
break;
case WRITER_IDLE:
eventType = "写空闲";
break;
case ALL_IDLE:
eventType = "读写空闲";
break;
}
System.out.println(ctx.channel().remoteAddress() + "-" + eventType);
//ctx.channel().close();
}
}
}
IdleStateHandler 是 netty 提供的处理空闲状态的处理器,其有 3 个重要的属性:
// 读空闲时间,表示多长时间没有读,就发送一个心跳检测包检测连接状态
private final long readerIdleTimeNanos;
// 写空闲时间,表示多长时间没有写,就发送一个心跳检测包检测连接状态
private final long writerIdleTimeNanos;
// 读写空闲时间,表示多长时间即没有读也没有写,就发送一个心跳检测包,检测连接状态
private final long allIdleTimeNanos;
当 netty 满足上述 3 个条件的其中一个时会触发 IdleStateEvent 事件,并将该事件传递给 pipeline 中的下一个 handler,触发下一个 handler 的 userEventTriggered() 事件,因此我们需要在 pipeline 中添加一个 handler(可自定义) 去处理该 IdleStateEvent 事件。
protected void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
ctx.fireUserEventTriggered(evt);
}
以上代码是 netty 触发 IdleStateEvent 的源码,效仿着我们也可以自定义事件类型并调用 ChannelHandlerContext 的 fireUserEventTriggered() 触发交由下一个 handler 处理。
三、通过WebSocket实现服务端和客户端的长连接
Http 协议是无状态的,浏览器和服务器间每一次请求 - 响应都会重新创建连接,基于 webSocket 的全双工的交互打破了 Http 协议多次请求的约束,实现了长连接, 服务器可以主动发送消息给浏览器。客户端浏览器和服务器端可以相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器也会感知。
public class WebSocketServer {
public static void main(String[] args) throws Exception {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup);
serverBootstrap.channel(NioServerSocketChannel.class);
serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));
serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// 因为基于 http 协议,使用 http 的编码和解码器
pipeline.addLast(new HttpServerCodec());
// 以块的方式写
pipeline.addLast(new ChunkedWriteHandler());
// http 数据在传输过程中是分段传输的, HttpObjectAggregator 可以将多个段聚合,着就是为什么当浏览器发送大量数据时,会发出多次 http 请求
pipeline.addLast(new HttpObjectAggregator(8192));
// WebSocket 的数据以帧(frame)的形式传递,WebSocketFrame 下有6个子类,浏览器请求 ws://localhost:7000/hello,WebSocketServerProtocolHandler的
// 核心功能是将 http 协议升级为 ws 协议,保持长连接
pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
// 自定义的handler,处理业务
pipeline.addLast(new TextWebSocketFrameHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
/**
* TextWebSocketFrame 表示一个文本帧(frame)
*/
class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
System.out.println("服务器收到消息:" + msg.text());
ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:" + LocalDateTime.now() + " " + msg.text()));
}
/**
* 当和客户端建立连接时触发
*
* @param ctx
* @throws Exception
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
// longText是唯一的,shortText不是唯一的
System.out.println("handlerAdded被调用:" + ctx.channel().id().asLongText());
System.out.println("handlerAdded被调用:" + ctx.channel().id().asShortText());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerRemoved 被调用:" + ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("发生异常:" + cause.getMessage());
ctx.close();
}
}
客户端一般都是浏览器,我们需要在浏览器端创建WebSocket对象,并给该对象绑定一些事件。
<html>
<body>
<script>
var socket;
if (window.WebSocket) {// 判断浏览器是否支持WebSocket
socket = new WebSocket("ws://localhost:7000/hello");
// 相当于channelRead0,ev 收到服务器端发送的消息
socket.onmessage = function (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + ev.data;
}
// 相当于连接开启(感知到连接开启)
socket.onopen = function (ev) {
var rt = document.getElementById("responseText");
rt.value = "连接开启了..."
}
socket.onclose = function (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n连接关闭了..."
}
} else {
alert("当前浏览器不支持 WebSocket")
}
function send(message) {
if (!window.socket) {// 判断socket是否创建好
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(message)
} else {
alert("连接没有开启")
}
}
</script>
<form onsubmit="return false">
<textarea name="message" style="height: 300px;width: 300px"></textarea>
<input type="button" value="发生消息" onclick="send(this.form.message.value)">
<textarea id="responseText" style="height: 300px;width: 300px"></textarea>
<input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>