六、Netty核心模块组件
6.1 类分析
6.1.1 Bootstrap、ServerBootstrap
-
Bootstrap是引导类,一个Netty应用通常由一个Bootstrap开始,主要作用是配置整个Netty程序,串联各个组件,Netty中Bootstrap类是客户端程序的启动引导类,ServerBootstrap是服务端启动引导类。 -
常见方法如下图
-
BootStrap
-
ServerBootStrap
-
父类AbstractBootstrap
-
6.1.2 Future、ChannelFuture
Netty 中所有的 IO 操作都是异步的,不能立刻得知消息是否被正确处理。但是可以过一会等它执行完成或者直接注册一个监听,具体的实现就是通过 Future 和 ChannelFuture,他们可以注册一个监听,当操作执行成功或失败时监听会自动触发注册的监听事件
6.1.3 Channel
Netty网络通信的组件,能够用于执行网络I/O操作。- 通过
Channel可获得当前网络连接的通道的状态 - 通过
Channel可获得网络连接的配置参数(例如接收缓冲区大小) Channel提供异步的网络I/O操作(如建立连接,读写,绑定端口),异步调用意味着任何I/O调用都将立即返回,并且不保证在调用结束时所请求的I/O操作已完成- 调用立即返回一个
ChannelFuture实例,通过注册监听器到ChannelFuture上,可以I/O操作成功、失败或取消时回调通知调用方 - 支持关联
I/O操作与对应的处理程序 - 不同协议、不同的阻塞类型的连接都有不同的
Channel类型与之对应,常用的Channel类型:NioSocketChannel,异步的客户端TCPSocket连接。NioServerSocketChannel,异步的服务器端TCPSocket连接。NioDatagramChannel,异步的UDP连接。NioSctpChannel,异步的客户端Sctp连接。NioSctpServerChannel,异步的Sctp服务器端连接,这些通道涵盖了UDP和TCP网络IO以及文件IO。
6.1.4 Selector
Netty基于Selector对象实现I/O多路复用,通过Selector一个线程可以监听多个连接的Channel事件。- 当向一个
Selector中注册Channel后,Selector内部的机制就可以自动轮询(Select)这些注册的Channel是否有已就绪的I/O事件(例如可读,可写,网络连接完成等),这样程序就可以很简单地使用一个线程高效地管理多个Channel
6.1.5 ChannelHandler及其实现类
-
ChannelHandler是一个接口,处理I/O事件或拦截I/O操作,并将其转发到其ChannelPipeline(业务处理链)中的下一个处理程序。 -
ChannelHandler本身并没有提供很多方法,因为这个接口有许多的方法需要实现,方便使用期间,可以继承它的子类 -
ChannelHandler及其实现类如下图 -
根据第五章Netty模型-编码实例中,我们需要自定义一个
Handler集成ChannelInboundHandlerAdapter,然后通过重写方法实现具体业务逻辑,常用的重写方法如下图
6.1.6 Pipeline和ChannelPipeline(重点)
ChannelPipeline 是一个重点:
ChannelPipeline是一个Handler的集合,它负责处理和拦截inbound或者outbound的事件和操作,相当于一个贯穿Netty的链。(也可以这样理解:ChannelPipeline是保存ChannelHandler的List,用于处理或拦截Channel的入栈事件和出栈操作)ChannelPipeline实现了一种高级形式的拦截过滤器模式(类似责任链模式),使用户可以完全控制事件的处理方式,以及Channel中各个的ChannelHandler如何相互交互- 在
Netty中每个Channel都有且仅有一个ChannelPipeline与之对应,它们的组成关系如下图
-
最常用的方法如下图
6.1.7 ChannelHandlerContext
-
保存
Channel相关的所有上下文信息,同时关联一个ChannelHandler对象 -
即
ChannelHandlerContext中包含一个具体的事件处理器ChannelHandler,同时ChannelHandlerContext中也绑定了对应的pipeline和Channel的信息,方便对ChannelHandler进行调用。 -
常用方法如下图
6.1.8 ChannelOption
-
Netty在创建Channel实例后,一般都需要设置ChannelOption参数。 -
ChannelOption常用参数如下图
6.1.9 EventLoopGroup及其实现类NioEventLoopGroup
-
EventLoopGroup是一组EventLoop的抽象,Netty为了更好的利用多核CPU资源,一般会有多个EventLoop同时工作,每个EventLoop维护着一个Selector实例。 -
EventLoopGroup提供next接口,可以从组里面按照一定规则获取其中一个EventLoop来处理任务。在Netty服务器端编程中,我们一般都需要提供两个EventLoopGroup,例如:BossEventLoopGroup和WorkerEventLoopGroup。 -
通常一个服务端口即一个
ServerSocketChannel对应一个Selector和一个EventLoop线程。BossEventLoop负责接收客户端的连接并将SocketChannel交给WorkerEventLoopGroup来进行IO处理,如下图所示- 通常情况下,
BossEventLoopGroup是一个单线程的EventLoop(处理连接单线程就够了),EventLoop维护一个注册了ServerSocketChannel的Selector实例,BossEventLoop不断轮询Selector将连接事件分离出来。 BossEventLoopGroup收到OP_ACCEPT事件,然后将收到的SocketChannel交给WorkerEventLoopGroup,WorkerEventLoopGroup通过next选择其中一个EventLoop将SocketChannel注册到其维护的Selector,并对其后续IO事件进行处理
- 通常情况下,
-
常用方法如下图
6.1.10 Unpooled
-
Netty提供一个专门用来操作缓冲区(即Netty的数据容器)的工具类 -
常用方法如下图(写入数据,返回
ByteBuf对象,类似NIO中的ByteBuffer) -
编码举例说明
package com.nic.netty.buf; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.CharsetUtil; /** * Description: * ByteBuf举例说明测试 * * @author james * @date 2021/7/22 10:59 */ public class NettyByteBufTest { public static void main(String[] args) { //创建一个ByteBuf //说明 //1. 创建 对象,该对象包含一个数组arr , 是一个byte[10] //2. 在netty 的buffer中,不需要使用flip 进行反转,底层维护了 readerindex 和 writerIndex //3. 通过 readerindex 和 writerIndex 和 capacity, 将buffer分成三个区域 // 0---readerindex 已经读取的区域 // readerindex---writerIndex , 可读的区域 // writerIndex -- capacity, 可写的区域 ByteBuf buffer = Unpooled.buffer(10); for (int i = 0; i < 10; i++) { buffer.writeByte(i); } System.out.println("capacity = " + buffer.capacity()); for (int i = 0; i < buffer.capacity(); i++) { //两者输出相同 System.out.println(buffer.getByte(i));// 0 1 2 3 4 5 6 7 8 9 System.out.println(buffer.readByte());// 0 1 2 3 4 5 6 7 8 9 System.out.println("-----------------"); } System.out.println("========================================="); ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world!", CharsetUtil.UTF_8); if (byteBuf.hasArray()) { byte[] array = byteBuf.array(); System.out.println(new String(array, CharsetUtil.UTF_8)); System.out.println("byteBuf = " + byteBuf); //偏移量 System.out.println(byteBuf.arrayOffset()); //当前读到的位置 System.out.println(byteBuf.readerIndex()); //当前可写的位置 System.out.println(byteBuf.writerIndex()); //buf的容量 System.out.println(byteBuf.capacity()); //执行readByte之后,readerIndex会+1 // System.out.println(byteBuf.readByte()); // System.out.println(byteBuf.readerIndex()); System.out.println(byteBuf.getByte(0)); //可读字节数 //以上调用readByte()之后,可读字节数会-1 System.out.println("len = " + byteBuf.readableBytes()); for (int i = 0; i < byteBuf.readableBytes(); i++) { System.out.println((char) byteBuf.getByte(i)); } //自定义开头和长度读取buf中的内容 System.out.println(byteBuf.getCharSequence(0, 4, CharsetUtil.UTF_8)); System.out.println(byteBuf.getCharSequence(4, 8, CharsetUtil.UTF_8)); } } }
6.2 编码实例(群聊系统)
实例要求:
注:功能与第三章4.3相同,只不过实现方式不同,这边通过Netty实现
- 编写一个
Netty群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞) - 实现多人群聊
- 服务器端:可以监测用户上线,离线,并实现消息转发功能
- 客户端:通过
channel可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)
测试步骤:
-
启动
Netty服务端 -
然后分别启动客户端(1)(2)(3)(4),服务端会分别看到4个客户端上线的消息,客户端也会分别收到其他客户端加入聊天的消息,由于客户端4最后加入,所以不会受到其他客户端加入聊天的消息
-
客户端1发送消息,其他客户端都收到了消息
代码如下:
-
服务端
package com.nic.netty.groupchat; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; /** * Description: * Netty群聊系统服务端 * * @author james * @date 2021/7/22 11:21 */ public class GroupChatServer { private int port; public GroupChatServer(int port) { this.port = port; } public static void main(String[] args) { new GroupChatServer(7102).listen(); } public void listen() { NioEventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(4); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.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.addLast("decoder", new StringDecoder()) .addLast("encoder", new StringEncoder()) .addLast(new GroupChatServerHandler()); } }); System.out.println("netty 服务器 is ready..."); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); channelFuture.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } -
服务端自定义handler
package com.nic.netty.groupchat; import cn.hutool.core.date.DateUtil; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.util.concurrent.GlobalEventExecutor; /** * Description: * SimpleChannelInboundHandler和ChannelInboundHandlerAdapter区别: * SimpleChannelInboundHandler会负责释放指向保存该消息的ByteBuf的内存引用。 * 而ChannelInboundHandlerAdapter在其时间节点上不会释放消息,而是将消息传递给下一个ChannelHandler处理。 * * @author james * @date 2021/7/22 11:26 */ public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> { //channel组,管理所有channel //GlobalEventExecutor.INSTANCE 全局时间执行器,单例 private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); //以下重写方法执行顺序 // handlerAdd -> channelActive -> channelInactive -> handlerRemoved // 客户端 writeAndFlush之后,触发channelRead0 /** * 连接建立就执行 * * @param ctx * @throws Exception */ @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); System.out.println("handlerAdd " + channel.remoteAddress()); //将上线的客户推送给其他客户端 //此方法会将group中所有的channel都写一遍 CHANNEL_GROUP.writeAndFlush("[客户端] " + channel.remoteAddress() + " 加入聊天 " + DateUtil.now() + " \n"); CHANNEL_GROUP.add(channel); } /** * 断开连接就执行 * * @param ctx * @throws Exception */ @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); System.out.println("handlerRemoved " + channel.remoteAddress()); CHANNEL_GROUP.writeAndFlush("[客户端] " + channel.remoteAddress() + " 退出聊天 " + DateUtil.now() + " \n"); System.out.println("channelGroup size = " + CHANNEL_GROUP.size()); } /** * 表示channel处于活动状态,与handlerAdded区分开 * 先channelActive,然后handlerAdd * * @param ctx * @throws Exception */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("channelActive " + ctx.channel().remoteAddress()); System.out.println(ctx.channel().remoteAddress() + " 上线了 " + DateUtil.now()); } /** * channel处于非活动状态,与handlerRemoved区分开 * * @param ctx * @throws Exception */ @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("channelInactive " + ctx.channel().remoteAddress()); System.out.println(ctx.channel().remoteAddress() + " 离线了 " + DateUtil.now()); } @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { Channel channel = ctx.channel(); System.out.println("channelRead0 " + channel.remoteAddress()); CHANNEL_GROUP.forEach(cg -> { //判断是否是当前channel,不是就转发消息 if (cg != channel) { cg.writeAndFlush("[客户端] " + channel.remoteAddress() + " 发送了消息 " + msg + " " + DateUtil.now() + "\n"); } else { cg.writeAndFlush("[自己] 发送了消息" + msg + " " + DateUtil.now()); } }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); } } -
客户端
package com.nic.netty.groupchat; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import java.util.Scanner; /** * Description: * Netty群聊系统客户端 * * @author james * @date 2021/7/22 13:44 */ public class GroupChatClient { private String host; private int port; public GroupChatClient(String host, int port) { this.host = host; this.port = port; } public static void main(String[] args) { new GroupChatClient("127.0.0.1", 7102).run(); } public void run() { 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()) .addLast("encoder", new StringEncoder()) .addLast(new GroupChatClientHandler()); } }); ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); Channel channel = channelFuture.channel(); System.out.println("client channel address = " + channel.remoteAddress()); Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()) { String str = scanner.nextLine(); channel.writeAndFlush(str); } } catch (Exception e) { e.printStackTrace(); } finally { group.shutdownGracefully(); } } } -
客户端自定义handler
package com.nic.netty.groupchat; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; /** * Description: * * @author james * @date 2021/7/22 13:49 */ public class GroupChatClientHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("client channelRead0 = " + msg.trim()); } }
6.3 编码实例(心跳检测)
实例要求:
- 编写一个
Netty心跳检测机制案例,当服务器超过3秒没有读时,就提示读空闲 - 当服务器超过
5秒没有写操作时,就提示写空闲 - 实现当服务器超过
7秒没有读或者写操作时,就提示读写空闲
测试步骤:
-
启动
HeartBeatServer服务端 -
启动6.2群聊系统中的客户端(不需要专门写一个客户端,只是为了测试心跳),服务端3秒后、5秒后、7秒后分别会打印出空闲的信息
读空闲每隔3秒打印一条消息,写空闲每隔5秒打印,读写空闲每隔7秒打印
代码如下:
-
服务端
package com.nic.netty.heartbeat; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.timeout.IdleStateHandler; /** * Description: * Netty心跳检测服务 * * @author james * @date 2021/7/22 14:20 */ public class HeartBeatServer { private int port; public HeartBeatServer(int port) { this.port = port; } public static void main(String[] args) { new HeartBeatServer(7102).listen(); } public void listen() { NioEventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(4); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); //加入netty提供 IdleStateHandler /** * 说明 * 1. IdleStateHandler 是netty 提供的处理空闲状态的处理器 * 2. long readerIdleTime : 表示多长时间没有读, 就会发送一个心跳检测包检测是否连接 * 3. long writerIdleTime : 表示多长时间没有写, 就会发送一个心跳检测包检测是否连接 * 4. long allIdleTime : 表示多长时间没有读写, 就会发送一个心跳检测包检测是否连接 * * 当 IdleStateEvent 触发后 , 就会传递给管道 的下一个handler去处理 * 通过调用(触发)下一个handler 的 userEventTiggered , 在该方法中去处理 IdleStateEvent(读空闲,写空闲,读写空闲) */ pipeline .addLast(new IdleStateHandler(3, 5, 7)) .addLast(new HeartBeatServerHandler()); } }); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); channelFuture.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } -
服务端自定义handler
package com.nic.netty.heartbeat; import cn.hutool.core.date.DateUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.IdleStateEvent; /** * Description: * * @author james * @date 2021/7/22 14:27 */ public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter { @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { System.out.println("userEventTriggered"); IdleStateEvent idleStateEvent = (IdleStateEvent) evt; String eventType = ""; switch (idleStateEvent.state()) { case READER_IDLE: eventType = "读空闲"; break; case WRITER_IDLE: eventType = "写空闲"; break; case ALL_IDLE: eventType = "读写空闲"; break; default: break; } System.out.println(ctx.channel().remoteAddress() + " 超时 " + eventType + " 当前时间:" + DateUtil.now()); System.out.println("服务器做处理。。。"); } } }
6.4 编码实例(WebSocket实现长连接)
实例要求:
Http协议是无状态的,浏览器和服务器间的请求响应一次,下一次会重新创建连接。- 要求:实现基于
WebSocket的长连接的全双工的交互 - 改变
Http协议多次请求的约束,实现长连接了,服务器可以发送消息给浏览器 - 客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知
测试步骤:
-
启动
WebSocketServer服务端 -
访问index.html,会出现"连接开启了"
-
在发消息框中输入消息,点击发送,
WebSocketServer控制台会出现浏览器发送的消息,内容框中会出现服务器回复的消息
代码如下:
-
服务端
package com.nic.netty.websocket; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import io.netty.handler.stream.ChunkedWriteHandler; /** * Description: * WebSocket 实现长连接服务端 * * @author james * @date 2021/7/22 14:54 */ public class WebSocketServer { private int port; public WebSocketServer(int port) { this.port = port; } public static void main(String[] args) { new WebSocketServer(7103).listen(); } public void listen() { NioEventLoopGroup bossGroup = new NioEventLoopGroup(1); NioEventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline //基于http协议 .addLast(new HttpServerCodec()) //以块方式写,添加ChunkedWriteHandler处理器 .addLast(new ChunkedWriteHandler()) //http传输过程是分段的,HttpObjectAggregator可以将多个段聚合 .addLast(new HttpObjectAggregator(8 * 1024)) .addLast(new WebSocketServerProtocolHandler("/hello")) .addLast(new WebSocketServerHandler()); } }); ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); channelFuture.channel().closeFuture().sync(); } catch (Exception e) { e.printStackTrace(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } -
服务端自定义handler
package com.nic.netty.websocket; import cn.hutool.core.date.DateUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; /** * Description: * * @author james * @date 2021/7/22 14:58 */ public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { System.out.println("channelRead0 = " + msg.text()); ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间:" + DateUtil.now() + " " + msg.text())); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { //id表示唯一的值, longText唯一,shortText不唯一 System.out.println("handlerAdded long id = " + ctx.channel().id().asLongText()); System.out.println("handlerAdded short id = " + ctx.channel().id().asShortText()); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { System.out.println("handlerRemoved long id = " + ctx.channel().id().asLongText()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("exceptionCaught = " + cause.getMessage()); ctx.close(); } } -
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>hello websocket</title> </head> <body> <script> var socket; //判断浏览器是否支持websocket if (window.WebSocket) { socket = new WebSocket("ws://localhost:7103/hello"); //onmessage 相当于channelRead0 //data 服务端回复的消息 socket.onmessage = function (data) { var responseText = document.getElementById("responseText"); console.log(data) responseText.value = responseText.value + "\n" + data.data; } //相当于handlerAdded socket.onopen = function (data) { var responseText = document.getElementById("responseText"); responseText.value = "连接开启了。。。" } socket.onclose = function (data) { var responseText = document.getElementById("responseText"); responseText.value = responseText.value + "\n连接关闭了。。。" } } else { alert("当前浏览器不支持websocket") } function send(msg) { if (!window.socket) { return; } if (socket.readyState === WebSocket.OPEN) { socket.send(msg); //清空聊天框 document.getElementById("requestText").value = ''; } else { alert("连接未开启。。。") } } </script> <form onsubmit="return false"> <div style="text-align: center"> <textarea name="message" id="requestText" style="height: 300px; width: 500px"></textarea> <input type="button" value="发消息" onclick="send(this.form.message.value)"> </div> <div style="text-align: center"> <textarea id="responseText" style="height: 300px; width: 500px"></textarea> <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''"> </div> </form> </body> </html>
完整代码
https://github.com/beiJxx/netty_test
资料参考