1 概述

(1) Http协议是无状态的,浏览器和服务器间的请求响应一次,下ー次会重新创建连接。
(2) 要求:实现基于 websockete的长连接的全双工的交互。
(3) 改变Http协议多次请求的约束,实现长连接了,服务器可以发送消息给浏览器。
(4) 客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知。

2 实现

2.1 WebSocketServerConsts

public final class WebSocketServerConsts {private WebSocketServerConsts() {}public static final Integer port = 8888;}

2.2 WebSocketHandler

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {@Overrideprotected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {System.out.println("服务器接收到消息:" + msg.text());//回复消息ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间" + LocalDateTime.now() + " " + msg.text()));}/*** 客户端连接后*/@Overridepublic void handlerAdded(ChannelHandlerContext ctx) throws Exception {System.out.println("handlerAdded 被调用" + ctx.channel().id().asLongText());System.out.println("handlerAdded 被调用" + ctx.channel().id().asShortText());}/***客户端断开连接时触发*/@Overridepublic void handlerRemoved(ChannelHandlerContext ctx) throws Exception {System.out.println("handlerRemoved 被调用" + ctx.channel().id().asLongText());}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {System.out.println("发生异常" + cause.getMessage());ctx.channel();}
}

2.3 WebSocketServerChannelInitializer

public class WebSocketServerChannelInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();//http 编码、解码器pipeline.addLast(new HttpServerCodec());//以块的方式写pipeline.addLast(new ChunkedWriteHandler());//http数据在传输过程中是分段的,HttpObjectAggregator可以将多个段聚合pipeline.addLast(new HttpObjectAggregator(8192));//websocketServerProtocolHandler,将http协议升级为ws协议,浏览器请求时uri为 ws://localhost:8888/hellopipeline.addLast(new WebSocketServerProtocolHandler("/hello"));//自定义handlerpipeline.addLast(new WebSocketHandler());}
}

2.4 WebSocketServer

public class WebSocketServer {public static void main(String[] args) {EventLoopGroup bossGroup = new NioEventLoopGroup(1);EventLoopGroup workerGroup = new NioEventLoopGroup();try {ServerBootstrap serverBootstrap = new ServerBootstrap();serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new WebSocketServerChannelInitializer());ChannelFuture channelFuture = serverBootstrap.bind(WebSocketServerConsts.port).sync();System.out.println("服务器已经开启......");channelFuture.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}}

2.5 hello.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>WebSocket</title>
</head>
<body><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" name="responseText" style="height: 300px;width: 300px;"></textarea><input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''"></form><script>var socket;if (window.WebSocket) {socket = new WebSocket("ws://localhost:8888/hello");//接收服务器消息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.WebSocket) {return;}if (socket.readyState == WebSocket.OPEN) {socket.send(message);} else {alert("连接没有开启");}}</script></body>
</html>

3 测试

关闭浏览器后:

Netty集成WebSocket实现客户端、服务端长连接相关推荐

  1. 客户端与服务端长连接的几种方式

    客户端与服务端长连接的几种方式 前言 一.ajax 轮询 二.long poll 长轮询 三.iframe 长连接 四.WebSocket 前言 在日常 Web 项目中,通常使用的是短连接.即一个 R ...

  2. SpringBoot集成WebSocket案例:服务端与客户端消息互通

    pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="htt ...

  3. 京东的Netty实践,京麦TCP网关长连接容器架构

    背景 早期京麦搭建 HTTP 和 TCP 长连接功能主要用于消息通知的推送,并未应用于 API 网关.随着逐步对 NIO 的深入学习和对 Netty 框架的了解,以及对系统通信稳定能力越来越高的要求, ...

  4. Java Websocket实例【服务端与客户端实现全双工通讯】

    Java Websocket实例[服务端与客户端实现全双工通讯] 现很多网站为了实现即时通讯,所用的技术都是轮询(polling).轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发 出HTTP ...

  5. netty 游戏服务器框图_基于Netty和WebSocket协议实现Web端自动打印订单服务方法与流程...

    本发明涉及电子商务技术领域,尤其涉及一种基于netty和websocket协议实现web端自动打印订单服务方法. 背景技术: 电子商务是以信息网络技术为手段,以商品交换为中心的商务活动:也可理解为在互 ...

  6. Node.js联机游戏——gobang五子棋(客户端+服务端+websocket的双人游戏)

    Node.js联机游戏--gobang五子棋(客户端+服务端+websocket的双人游戏) 五子棋的基本结构 ~·基本画图 ~·判断机制 ~···横向/竖向判断 ~···斜向判断 搭建服务器阶段 ~ ...

  7. ZooKeeper客户端源码(一)——向服务端建立连接+会话建立+心跳保持长连接

    首发CSDN:徐同学呀,原创不易,转载请注明源链接.我是徐同学,用心输出高质量文章,希望对你有所帮助. 一.从ZooKeeper实例初始化开始 ZooKeeper 提供了原生的客户端库,虽然不好用,但 ...

  8. netty源码学习之服务端客户端初始化

    文章目录 1. AbstractBootstrap类简介 1.1. 核心方法 2. netty服务端创建 2.1. 服务端启动入口 2.2. doBind()方法 2.3. netty服务初始化 2. ...

  9. http协议与https协议+UDP协议和TCP协议+WebSocket协议下服务端主动去发送信息+对称加密与非对称加密+get和post请求方式区别详解+浏览器内核以及jsj解析引擎

    TCP和UDP协议是TCP/IP协议的核心. 在TCP/IP网络体系结构中,TCP(传输控制协议,Transport Control Protocol).UDP(用户数据报协议,User Data P ...

  10. 【Netty系列_3】Netty源码分析之服务端channel

    highlight: androidstudio 前言 学习源码要有十足的耐性!越是封装完美的框架,内部就越复杂,源码很深很长!不过要抓住要点分析,实在不行多看几遍,配合debug,去一窥优秀框架的精 ...

最新文章

  1. 51nod 1282 时钟
  2. SQL Try Catch
  3. wxpython实现鼠标拖动事件
  4. magento php mysql,安装lnmp nginx php mysql环境 -magento
  5. 华为交换机的一些OID
  6. mysql客户端hang_MySQL所有操作hang住了,怎么破?
  7. 为什么python工程师掌握这些就够了_Python工程师薪资飙升,Python这些技能你掌握了吗...
  8. mdb文件取消隐藏_webshellphp隐藏技巧
  9. 20101022网站更新部署
  10. Hadoop学习笔记—13.分布式集群中节点的动态添加与下架
  11. 悟透delphi 第十一章 面向对象数据库基础
  12. 图片与路径(Path)的应用
  13. 订单页面添加收货地址html,添加收货地址展示
  14. esxi能直通的显卡型号_2020最适合新手CG玩家的电脑配置【显卡--专业卡、游戏卡】...
  15. ubuntu14.04安装360随身wifi 2代
  16. Java--深入理解字符串的String#intern()方法奥妙之处
  17. 西游记笔记与想法(1)
  18. 交比不变性 matlab,交比 | 迪沙格定理
  19. 华为应用市场,浏览器PC版
  20. linux下安装 postgresql 14

热门文章

  1. c语言 字符串转浮点型函数
  2. MFC Windows 程序设计(二)-初尝禁果
  3. 数论入门 2021-2-28
  4. 计算机的屏幕为什么成黑色,电脑液晶显示器老是黑屏怎么回事
  5. java中的输入输出流概念_Java输入输出(IO)和流的基本概念
  6. eclipse优化:最详细
  7. go编译成linux可执行,Golang 编译Mac、Linux、Windows多平台可执行程序
  8. IE7和IE8的CSS样式不兼容
  9. BCH编译码的matlab性能分析
  10. 电影网络首播后喜剧场上线,搅局者加速行业重塑