Bootstrap、ServerBootstrap
-
Bootstrap 意思是引导,一个 Netty 应用通常由一个 Bootstrap 开始,主要作用是配置整个 Netty 程序,串联 各个组件,Netty 中 Bootstrap 类是客户端程序的启动引导类,ServerBootstrap 是服务端启动引导类
-
常见的方法有
-
public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup)
该方法用于服务器端, 用来设置两个 EventLoop
-
public B group(EventLoopGroup group)
该方法用于客户端,用来设置一个 EventLoop
-
public B channel(Class<? extends C> channelClass)
该方法用来设置一个服务器端的通道实现
-
public B option(ChannelOption option, T value)
用来给 ServerChannel 添加配置
-
public ServerBootstrap childOption(ChannelOption childOption, T value)
用来给接收到的通道添加配置
-
public B handler(ChannelHandler handler)
在客户端连接前的请求进行handler处理,handler()是发生在初始化的时候
-
public ServerBootstrap childHandler(ChannelHandler childHandler)
该方法用来设置业务处理类(自定义的handler),处理客户端连接之后的handler,childHandler()是发生在客户端连接之后
-
public ChannelFuture bind(int inetPort)
该方法用于服务器端,用来设置占用的端口号
-
public ChannelFuture connect(String inetHost, int inetPort)
该方法用于客户端,用来连接服务器端
-
Future、ChannelFuture
Netty 中所有的 IO 操作都是异步的,不能立刻得知消息是否被正确处理。但是可以过一会等它执行完成或 者直接注册一个监听,具体的实现就是通过 Future 和 ChannelFutures,他们可以注册一个监听,**当操作执行成功 或失败时监听会自动触发注册的监听事件 **
常见的方法有
- Channel channel() 返回当前正在进行 IO 操作的通道
- ChannelFuture sync() 等待异步操作执行完毕
Channel
- Netty 网络通信的组件,能够用于执行网络 I/O 操作
- 通过 Channel 可获得当前网络连接的通道的状态
- 通过 Channel 可获得 网络连接的配置参数 (例如接收缓冲区大小)
- Channel 提供异步的网络 I/O 操作(如建立连接,读写,绑定端口),异步调用意味着任何 I/O 调用都将立即返 回,并且不保证在调用结束时所请求的 I/O 操作已完成
- 调用立即返回一个 ChannelFuture 实例,通过注册监听器到 ChannelFuture 上,可以 I/O 操作成功、失败或取 消时回调通知调用方
- 支持关联 I/O 操作与对应的处理程序
- 不同协议、不同的阻塞类型的连接都有不同的 Channel 类型与之对应,常用的 Channel 类型:
- NioSocketChannel,异步的客户端 TCP Socket 连接
- NioServerSocketChannel,异步的服务器端 TCP Socket 连接
- NioDatagramChannel,异步的 UDP 连接
- NioSctpChannel,异步的客户端 Sctp 连接
- NioSctpServerChannel,异步的 Sctp 服务器端连接,这些通道涵盖了 UDP 和 TCP 网络 IO 以及文件 IO
Selector
- Netty 基于 Selector 对象实现 I/O 多路复用,通过 Selector 一个线程可以监听多个连接的 Channel 事件
- 当向一个 Selector 中注册 Channel 后,Selector 内部的机制就可以自动不断地查询(Select) 这些注册的 Channel 是否有已就绪的 I/O 事件(例如可读,可写,网络连接完成等),这样程序就可以很简单地使用一个 线程高效地管理多个 Channel
ChannelHandler 及其实现类
-
ChannelHandler 是一个接口,处理 I/O 事件或拦截 I/O 操作,并将其转发到其 ChannelPipeline(业务处理链) 中的下一个处理程序
-
ChannelHandler 本身并没有提供很多方法,因为这个接口有许多的方法需要实现,方便使用期间,可以继承它 的子类
-
ChannelHandler 及其实现类一览图
-
我们经常需要自定义一个 Handler 类去继承 ChannelInboundHandlerAdapter,然后通过重写相应方法实现业务 逻辑,我们接下来看看一般都需要重写哪些方法
public class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelInboundHandler { public ChannelInboundHandlerAdapter() { } public void channelRegistered(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelRegistered(); } public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelUnregistered(); } //通道就绪事件 public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelActive(); } public void channelInactive(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelInactive(); } //通道读取数据事件 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ctx.fireChannelRead(msg); } //数据读取完毕事件 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelReadComplete(); } public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { ctx.fireUserEventTriggered(evt); } public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { ctx.fireChannelWritabilityChanged(); } //通道发生异常事件 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.fireExceptionCaught(cause); } }
Pipeline 和 ChannelPipeline
-
ChannelPipeline 是一个 Handler 的集合,它负责处理和拦截 inbound 或者 outbound 的事件和操作,相当于一个贯穿 Netty 的链。(也可以这样理解:ChannelPipeline 是 保存 ChannelHandler 的 List,用于处理或拦截 Channel 的入站事件和出站操作)
-
ChannelPipeline 是一个 Handler 的集合,它负责处理和拦截 inbound 或者 outbound 的事件和操作,相当于一个贯穿 Netty 的链。(也可以这样理解:ChannelPipeline 是 保存 ChannelHandler 的 List,用于处理或拦截 Channel 的入站事件和出站操作)
-
在 Netty 中每个 Channel 都有且仅有一个 ChannelPipeline 与之对应,它们的组成关系如下
- 一个 Channel 包含了一个 ChannelPipeline,而 ChannelPipeline 中又维护了一个由 ChannelHandlerContext 组成的双向链表,这个链表的头是HeadContext,链表的尾是TailContext,并且每个 ChannelHandlerContext 中又关联着一个 ChannelHandler
- 入站事件和出站事件在一个双向链表中,入站事件会从链表 head 往后传递到最后一个入站的 handler,出站事件会从链表 tail 往前传递到最前一个出站的 handler,两种类型的 handler 互不干扰
-
常用方法
- ChannelPipeline addFirst(ChannelHandler… handlers),把一个业务处理类(handler)添加到链中的第一个位置
- ChannelPipeline addLast(ChannelHandler… handlers),把一个业务处理类(handler)添加到链中的最后一个位置
ChannelHandlerContext
- 保存 Channel 相关的所有上下文信息,同时关联一个 ChannelHandler 对象
- 即 ChannelHandlerContext 中 包 含 一 个 具 体 的 事 件 处 理 器 ChannelHandler , 同 时ChannelHandlerContext 中也绑定了对应的 pipeline 和 Channel 的信息,方便对 ChannelHandler 进行调用
- 常用方法
- ChannelFuture close(),关闭通道
- ChannelOutboundInvoker flush(),刷新
- ChannelFuture writeAndFlush(Object msg) , 将 数 据 写 到 ChannelPipeline 中 当 前
- ChannelHandler 的下一个 ChannelHandler 开始处理(出站)
ChannelOption
-
Netty 在创建 Channel 实例后,一般都需要设置 ChannelOption 参数
-
ChannelOption 参数如下
-
ChannelOption.SO_BACKLOG
描述:对应 TCP/IP 协议 listen 函数中的 backlog 参数,用来初始化服务器可连接队列大小。服务端处理客户端连接请求是顺序处理的,所以同一时间只能处理一个客户端连接。多个客户端来的时候,服务端将不能处理的客户端连接请求放在队列中等待处理,backlog 参数指定了队列的大小。
-
ChannelOption.SO_KEEPALIVE
描述:一直保持连接活动状态
-
ChannelOption.TCP_NODELAY
描述:没有延迟
-
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 将连接事件分离出来
- 通常是 OP_ACCEPT 事件,然后将接收到的 SocketChannel 交给 WorkerEventLoopGroup
- WorkerEventLoopGroup 会由 next 选择其中一个 EventLoop来将这个 SocketChannel 注册到其维护的 Selector 并对其后续的 IO 事件进行处理
- 常用方法
- public NioEventLoopGroup(),构造方法
- public Future<?> shutdownGracefully(),断开连接,关闭线程
Unpooled 类
-
Netty 提供一个专门用来操作缓冲区(即Netty的数据容器)的工具类
-
常用方法如下所示
-
public static ByteBuf copiedBuffer(CharSequence string, Charset charset)
通过给定的数据和字符编码返回一个 ByteBuf 对象(类似于 NIO 中的 ByteBuffer 但有区别)
-
-
举例说明Unpooled 获取 Netty的数据容器ByteBuf 的基本使用
//创建一个ByteBuf //1.创建对象,该对象包含一个数组arr,是一个byte[10] //2.在netty的buffer中,不需要使用flip进行反转, // 底层维护了readerindex和writerindex 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)); }
debug运行一下
writerIndex会增加。使用getByte(i),readerIndex不会增加,替换成
System.out.println(buffer.readByte());
每读一次readerIndex就会增加1
//创建ByteBuf
ByteBuf buf = Unpooled.copiedBuffer("hello,world!", Charset.forName("utf-8"));
//使用相关的方法
if(buf.hasArray()){
byte[] content = buf.array();
//将content转为字符串
System.out.println(new String(content,Charset.forName("utf-8")));
System.out.println(buf.toString(CharsetUtil.UTF_8));
System.out.println(buf.arrayOffset());
System.out.println(buf.readerIndex());
System.out.println(buf.writerIndex());
System.out.println(buf.capacity());
System.out.println("----------------");
//可读的字节数
int len=buf.readableBytes();
System.out.println(len);
//取出各个字节
for(int i=0;i<len;i++){
System.out.print(buf.readerIndex()+":"+buf.readByte()+" ");
}
System.out.println("\n从第0个开始,读取4个:"+buf.getCharSequence(0,4,CharsetUtil.UTF_8));
System.out.println("从第4个开始,读取6个:"+buf.getCharSequence(4,6,CharsetUtil.UTF_8));
}
运行
hello,world!
hello,world!
0
0
12
64
----------------
12
0:104 1:101 2:108 3:108 4:111 5:44 6:119 7:111 8:114 9:108 10:100 11:33
从第0个开始,读取4个:hell
从第4个开始,读取6个:o,worl
群聊系统
编写一个 Netty 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
server
public class Server {
/**
* 监听端口
*/
private int port;
public Server(int port){
this.port=port;
}
//编写run方法处理客户端的请求
public void run(){
//创建两个线程组
EventLoopGroup bossGroup=new NioEventLoopGroup(1);
EventLoopGroup workerGroup=new NioEventLoopGroup();
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 {
//获取到pipeline
ChannelPipeline pipeline = ch.pipeline();
//向pipeline加入解码器
pipeline.addLast("decoder",new StringDecoder());
//向pipeline加入编码器
pipeline.addLast("encoder",new StringEncoder());
//加入自己的业务处理handler
pipeline.addLast(new ServerHandler());
}
});
System.out.println("服务器启动");
ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(port)).sync();
//监听关闭事件
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) {
new Server(50000).run();
}
}
serverHandler
public class ServerHandler extends SimpleChannelInboundHandler<String> {
/**
* 使用一个hashMap管理
*/
public static Map<User,Channel> channels=new ConcurrentHashMap<>();
/**
* 定义一个channel组,管理所有的channel
* GlobalEventExecutor.INSTANCE 是全局的时间执行器,是一个单利
*/
private static ChannelGroup channelGroup=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
private DateTimeFormatter formatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* @Description 表示连接建立,一旦连接,第一个被执行
* 将当前channel接入到channelGroup
* @date 2020/7/23 23:11
* @param ctx
* @return void
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
channelGroup.add(channel);
//将该客户端加入聊天的信息推送给其它在线的客户端
channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+"加入聊天\n");
//这里可以私聊
channels.put(new User(123456L),channel);
}
/**
* @Description 表示channel处于活跃状态,提示xxx上线
* @date 2020/7/23 23:18
* @param ctx
* @return void
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress()+"上线");
}
/**
* @Description 读取数据
* @date 2020/7/24 0:15
* @param ctx
* @param msg
* @return void
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//获取当前channel
Channel channel = ctx.channel();
//这里我们遍历一下,自己不需要获取自己的消息
for (Channel ch : channelGroup) {
if(ch!=channel) {
ch.writeAndFlush("[客户]"+ch.remoteAddress()+ LocalDateTime.now().format(formatter) +"发送消息:"+msg+"\n");
}else{
ch.writeAndFlush(LocalDateTime.now().format(formatter)+"发送了消息:"+msg+"[自己]\n");
}
}
}
/**
* @Description 处理异常
* @date 2020/7/23 23:29
* @param ctx
* @param cause
* @return void
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//关闭
ctx.close();
}
/**
* @Description 表示channel处于非活跃状态,提示xxx离线
* @date 2020/7/23 23:21
* @param ctx
* @return void
*/
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println(ctx.channel().remoteAddress()+LocalDateTime.now().format(formatter) +"离线");
}
/**
* @Description 断开连接,将xx客户端离开信息推送给当前在线的客户
* @date 2020/7/23 23:22
* @param ctx
* @return void
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
Channel channel = ctx.channel();
channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+LocalDateTime.now().format(formatter) +"离开聊天\n");
System.out.println("channelGroup的大小:"+channelGroup.size());
}
}
client
public class Client {
private final String host;
private final int port;
public Client(String host,int port){
this.host=host;
this.port=port;
}
public void run(){
NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
try {
bootstrap.group(eventExecutors)
.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("handler",new ClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress(host, port)).sync();
Channel channel = channelFuture.channel();
System.out.println("--------"+channel.localAddress()+"-----------");
//客户端需要输入信息,创建一个扫描器
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext()){
String str=scanner.nextLine();
//通过channel发送到服务器
channel.writeAndFlush(str);
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
eventExecutors.shutdownGracefully();
}
}
public static void main(String[] args) {
new Client("127.0.0.1",50000).run();
}
}
clientHandler
public class ClientHandler extends SimpleChannelInboundHandler<String> {
/**
* @Description 读取信息
* @date 2020/7/23 23:47
* @param ctx
* @param msg
* @return void
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg.trim());
}
}
测试
Netty 心跳检测机制案例
- 编写一个 Netty 心跳检测机制案例, 当服务器超过 3 秒没有读时,就提示读空闲
- 当服务器超过 5 秒没有写操作时,就提示写空闲
- 实现当服务器超过 7 秒没有读或者写操作时,就提示读写空闲
public class Server {
public static void main(String[] args) {
//创建两个线程组
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap=new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,128)
.childOption(ChannelOption.SO_KEEPALIVE,true)
.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:表示多长时间既没有读也没有写,就会发送一个心跳检测包,检测是否连接
5.当IdealStateEvent触发后,就会传递给管道的下一个handler去处理,
通过调用(触发)下一个handler的userEventTriggered(),在该方法中去处理
*/
pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
//加入一个对空闲检测进一步处理的handler(自定义)
pipeline.addLast(new ServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(50000)).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
public class ServerHandler extends ChannelInboundHandlerAdapter {
/**
* @Description 事件触发器
* @date 2020/7/24 0:51
* @param ctx
* @param evt
* @return void
*/
@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);
System.out.println("服务器做相应处理...");
}
}
}
- idleStateHandler 是netty 提供的处理空闲状态的处理器
- long readerIdleTime:表示多长时间没有读,就会发送一个心跳检测包,检测是否连接
- long writerIdleTime:表示多长时间没有写,就会发送一个心跳检测包,检测是否连接
- long allIdleTime:表示多长时间既没有读也没有写,就会发送一个心跳检测包,检测是否连接
- 当IdealStateEvent触发后,就会传递给管道的下一个handler去处理,通过调用(触发)下一个handler的userEventTriggered(),在该方法中去处理
WebSocket 编程实现服务器和客户端长连接
- Http 协议是无状态的, 浏览器和服务器间的请求响应一次,下一次会重新创建连接
- 要求:实现基于 webSocket 的长连接的全双工的交互
- 改变 Http 协议多次请求的约束,实现长连接了, 服务器可以发送消息给浏览器
- 客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知
server
public class server {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup=new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap=new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,128)
.childOption(ChannelOption.SO_KEEPALIVE,true)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//基于http协议,使用http的编码和解码器
pipeline.addLast(new HttpServerCodec());
//是以块的方式写,添加ChunkedWriteHandler处理器
pipeline.addLast(new ChunkedWriteHandler());
/*
说明:
1. HTTP数据在传输过程中分段,HttpObjectAggregator,就是可以将多个段聚合
2. 这就是为什么,当浏览器发送大量数据时,就是发出多次http请求
*/
pipeline.addLast(new HttpObjectAggregator(1024*8));
/*
说明:
1. 对应websocket,它的数据是以 帧(frame) 形式传递
2. 可以看成websocketFrame有下面有六个子类
3. 浏览器请求时:ws://localhost:50000/xxx
4. WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议,保持长连接
*/
pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
//自定义的handler,处理业务逻辑
pipeline.addLast(new ServerHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(50000)).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
当我们用POST方式请求服务器的时候,对应的参数信息是保存在message body中的,如果只是单纯的用HttpServerCodec是无法完全的解析Http POST请求的,因为HttpServerCodec只能获取uri中参数,所以需要加上HttpObjectAggregator。
serverHandler
/**
* @author codekiller
* @date 2020/7/24 13:56
* @Description TextWebSocketFrame类型,表示一个文本帧
*/
public class ServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
/**
* @Description 当web客户端连接后,触发方法
* @date 2020/7/24 14:03
* @param ctx
* @return void
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//id 表示唯一的一个值,LongText是唯一的,ShortText不是唯一的
System.out.println("handlerAdded 被调用"+ctx.channel().id().asLongText());
System.out.println("handlerAdded 被调用"+ctx.channel().id().asShortText());
}
/**
* @Description 读取数据
* @date 2020/7/24 13:59
* @param ctx
* @param msg
* @return void
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
System.out.println("服务端收到消息:"+msg.text());
//回复客户端
Channel channel = ctx.channel();
channel.writeAndFlush(new TextWebSocketFrame("服务器时间:"+ LocalDateTime.now()+" "+msg.text()));
}
/**
* @Description 异常处理
* @date 2020/7/24 14:06
* @param ctx
* @param cause
* @return void
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("异常发生 "+cause.getMessage());
ctx.close();
}
/**
* @Description 当web客户端断开连接后,触发方法
* @date 2020/7/24 14:05
* @param ctx
* @return void
*/
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerRemoved 被调用"+ctx.channel().id().asLongText());
System.out.println("handlerRemoved 被调用"+ctx.channel().id().asShortText());
}
}
界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<form onsubmit="return false">
<textarea id="message" 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>
<script>
let socket;
//判断当前浏览器是否支持webSocket编程
if(window.WebSocket){
socket =new WebSocket("ws://localhost:50000/hello");
//ev接受服务端回送的消息
socket.onmessage=(ev)=>{
let rt = document.getElementById("responseText");
rt.value=rt.value+"\n"+ev.data
}
//相当于连接开启(感知到连接开启)
socket.onopen=(ev)=>{
let rt = document.getElementById("responseText");
rt.value="连接已开启..."
}
//感知到连接关闭
socket.onclose=(ev)=>{
let rt = document.getElementById("responseText");
rt.value=rt.value+"\n"+"连接已关闭..."
}
}else{
alert("当前浏览器不支持webSocket编程")
}
//发送消息到服务器
function send(msg){
// if(!window.socket){
// return;
// }
if(socket.readyState===WebSocket.OPEN){
//通过socket发送消息
socket.send(msg)
}else{
alert("连接没有开启")
}
}
</script>
</html>
运行
发送请求
前台
后台