网络I/o编程模型18 netty通过websocket实现服务,客户端通信

一 需求描述

基于websocket的全双工的长连接,实现客户端和服务端之间信息的交互。比如客户端浏览器和服务器会相互感知,比如服务器关闭了,浏览器会感知;同样浏览器关闭了,服务器也会感知。

二 代码实现

1.服务端

package com.ljf.netty.netty.websocket;

import com.ljf.netty.netty.heartbeat.MyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
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;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: NettyWebSocketServer
 * @Description: TODO
 * @Author: liujianfu
 * @Date: 2022/06/04 12:00:07
 * @Version: V1.0
 **/
public class NettyWebSocketServer {
    public static void main(String[] args) {
        //创建两个线程组
        EventLoopGroup bossGroup=new NioEventLoopGroup(1);
        EventLoopGroup workerGroup=new NioEventLoopGroup();//8个NioEventLoop
        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());
                    //是以块方式写,添加chunkedwritehandler 处理器
                    pipeline.addLast(new ChunkedWriteHandler());
                    //当浏览器发送大量数据时,就会发出多次http请求,http数据在传输过程中是分段的。
                    pipeline.addLast(new HttpObjectAggregator(8192));
                    //websocket 它的数据是以帧的形式传递;WebSocketSeverProtocolHandler 核心功能是将http协议升级为ws协议,保持长连接
                    //浏览器请求是,ws://localhost:6000/hello 表示请求的uri
                    pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                    //自定义的handler,处理业f务逻辑
                    pipeline.addLast(new MyTextWebSocketFrameHandler());
                }
            });
            //启动服务器
            ChannelFuture channelFuture = serverBootstrap.bind("127.0.0.1",6666).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}

2.自定义处理类

package com.ljf.netty.netty.websocket;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

/**
 * @ClassName: MyTextWebSocketFrameHandler
 * @Description: TODO  这里的TextWebSocketFrame 表示类型,表示一个文本帧
 * @Author: liujianfu
 * @Date: 2022/06/04 16:36:39
 * @Version: V1.0
 **/
public class MyTextWebSocketFrameHandler 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()));
    }
    //有web客户端连接后,触发的方法
    public void handlerAdded(ChannelHandlerContext ctx){
        //id 表示唯一的值,LongText是唯一的;  shortText不是唯一
        System.out.println("handlerAdded 被调用:"+ctx.channel().id().asLongText());
        System.out.println("handlerAdded 被调用:"+ctx.channel().id().asShortText());
    }
    //有web客户端连接断开后,触发的方法
    public void handlerRemoved(ChannelHandlerContext ctx){
        System.out.println("handlerRemove 被调用:"+ctx.channel().id().asLongText());
    }
    //发生异常
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        System.out.println("异常发生:"+cause.getMessage());
        ctx.close();
    }

}

3. 前端页面

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Document</title>
  <script>
  var socket;
  //判断当前浏览器是否支持websocket
  if(window.WebSocket){
	  socket=new WebSocket("ws://127.0.0.1:6666/hello");
	  //相当于channelReado,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 sendInfo(message){
	  alert(message);
      if(!window.socket){
		  return ; //先判断socket是否创建好
	  }
	  if(socket.readyState==WebSocket.OPEN){
         //通过socket发送消息
		 socket.send(message);
	  }
	  else{
		  alert("连接没有开启...");
	  }
  }
  </script>
 </head>
 <body>
  <form onsubmit="return false">
  <textarea name="message" style="height:300px;width:300px"></textarea>
  <input type="button" value="发送消息" onclick="sendInfo(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>

4.查询结果 

1.服务端

 

2.页面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
精通并发与 netty 视频教程(2018)视频教程。 精通并发与netty视频教程(2018)视频教程 netty视频教程 Java视频教程目录: 1_学习的要义 2_Netty宏观理解 3_Netty课程大纲深度解读 4_项目环境搭建与Gradle配置 5_Netty执行流程分析与重要组件介绍 6_Netty回调与Channel执行流程分析 7_Netty的Socket编程详解 8_Netty客户连接与通信 9_Netty读写检测机制与长连接要素 10_NettyWebSocket的支援 11_Netty实现服务客户的长连接通信 12_Google Protobuf详解 13_定义Protobuf文件及消息详解 14_Protobuf完整实例详解 15_Protobuf集成Netty与多协议消息传 递 16_Protobuf多协议消息支援与工程最佳实践 17_Protobuf使用最佳实践与Apache Thrift介绍 18_Apache Thrift应用详解与实例剖析 19_Apache Thrift原理与架构解析 20_通过Apache Thrift实现Java与Python的RPC调用 21_gRPC深入详解 22_gRPC实践 23_Gradle Wrapper在Gradle项目构建中的最佳实践 24_gRPC整合Gradle与代码生成 25_gRPC通信示例与JVM回调钩子 26_gRPC服务器流式调用实现 27_gRPC双向流式数据通信详解 28_gRPC与Gradle流畅整合及问题解决的完整过程与思考 29_Gradle插件问题解决方案与Nodejs环境搭建 30_通过gRPC实现Java与Nodejs异构平台的RPC调用 31_gRPC在Nodejs领域中的静态代码生成及与Java之间的RPC通信 32_IO体系架构系统回顾与装饰模式的具体应用 33_Java NIO深入详解与体系分析 34_Buffer中各重要状态属性的含义与关系图解 35_Java NIO核心类源码解读与分析 36_文件通道用法详解 37_Buffer深入详解 38_NIO堆外内存与零拷贝深入讲解 39_NIO中Scattering与Gathering深度解析 40_Selector源码深入分析 41_NIO网络访问模式分析 42_NIO网络编程实例剖析 43_NIO网络编程深度解析 44_NIO网络客户编写详解 45_深入探索Java字符集编解码 46_字符集编解码全方位解析 47_Netty服务器与客户编码模式回顾及源码分析准备 48_Netty与NIO系统总结及NIO与Netty之间的关联关系分析 49_零拷贝深入剖析及用户空间与内核空间切换方式 50_零拷贝实例深度剖析 51_NIO零拷贝彻底分析与Gather操作在零拷贝中的作用详解 52_NioEventLoopGroup源码分析与线程数设定 53_Netty对Executor的实现机制源码分析 54_Netty服务初始化过程与反射在其中的应用分析 55_Netty提供的Future与ChannelFuture优势分析与源码讲解 56_Netty服务器地址绑定底层源码分析 57_Reactor模式透彻理解及其在Netty中的应用 58_Reactor模式与Netty之间的关系详解 59_Acceptor与Dispatcher角色分析 60_Netty的自适应缓冲区分配策略与堆外内存创建方式 61_Reactor模式5大角色彻底分析 62_Reactor模式组件调用关系全景分析 63_Reactor模式与Netty组件对比及Acceptor组件的作用分析 64_Channel与ChannelPipeline关联关系及模式运用 65_ChannelPipeline创建时机与高级拦截过滤器模式的运用 66_Netty常量池实现及ChannelOption与Attribute作用分析 67_Channel与ChannelHandler及ChannelHandlerContext之间的关系分析 68_Netty核心四大组件关系与构建方式深度解读 69_Netty初始化流程总结及Channel与ChannelHandlerContext作用域分析 70_Channel注册流程深度解读 71_Channel选择器工厂与轮询算法及注册底层实现 72_Netty线程模型深度解读与架构设计原则 73_Netty底层架构系统总结与应用实践 74_Netty对于异步读写操作的架构思想与观察者模式的重要应用 75_适配器模式与模板方法模式在入站处理器中的应用 76_Netty项目开发过程中常见且重要事项分析 77_Java NIO Buffer总结回顾与难点拓展 78_Netty

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值