Netty实现WebSocket长连接

约定不等于承诺〃 2022-09-06 13:27 341阅读 0赞
  1. WebSocket协议是使用单个TCP连接进行全双工通信的协议,浏览器与服务器使用一个长连接,可以双向数据传输,且服务器可以主动给浏览器推送数据。Netty是通过给通道绑定的管道,添加一个WebSocketServerProtocleHandler处理器,将http协议升级为WebSocket协议的,数据传输采用帧WebSocketFrame的形式,比如常用的文本帧TextWebSocketFrame传输文本数据。
  2. 服务器
  3. package com.tech.netty.netty.websocket;
  4. import io.netty.bootstrap.ServerBootstrap;
  5. import io.netty.channel.ChannelFuture;
  6. import io.netty.channel.ChannelInitializer;
  7. import io.netty.channel.ChannelPipeline;
  8. import io.netty.channel.nio.NioEventLoopGroup;
  9. import io.netty.channel.socket.SocketChannel;
  10. import io.netty.channel.socket.nio.NioServerSocketChannel;
  11. import io.netty.handler.codec.http.HttpObjectAggregator;
  12. import io.netty.handler.codec.http.HttpServerCodec;
  13. import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
  14. import io.netty.handler.logging.LogLevel;
  15. import io.netty.handler.logging.LoggingHandler;
  16. import io.netty.handler.stream.ChunkedWriteHandler;
  17. /**
  18. * @author lw
  19. * @since 2021/8/20
  20. */
  21. public class MyServer {
  22. public static void main(String[] args) throws InterruptedException {
  23. //创建2个线程组
  24. NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
  25. NioEventLoopGroup workerGroup = new NioEventLoopGroup();
  26. try{
  27. ServerBootstrap serverBootstrap = new ServerBootstrap();
  28. serverBootstrap.group(bossGroup,workerGroup)
  29. .channel(NioServerSocketChannel.class)
  30. .handler(new LoggingHandler(LogLevel.INFO))
  31. .childHandler(new ChannelInitializer<SocketChannel>() {
  32. @Override
  33. protected void initChannel(SocketChannel ch) throws Exception {
  34. ChannelPipeline pipeline = ch.pipeline();
  35. //因为基于http协议 使用http的编码器和解码器
  36. pipeline.addLast("HttpServerCodec",new HttpServerCodec())
  37. //以块方式写 添加ChunkedWriteHandler处理器
  38. .addLast("ChunkedWriteHandler", new ChunkedWriteHandler())
  39. //http传输过程中会分段 HttpObjectAggregator可以将多个段聚合
  40. //这就是为什么,当浏览器发送大量数据时,就会发多次http请求
  41. .addLast("HttpObjectAggregator",new HttpObjectAggregator(8192))
  42. //对应websocket 它的数据是以帧(WebSocketFrame)形式传递
  43. //浏览器请求时ws://localhost:7000/hello表示请求的uri
  44. //WebSocketServerProtocolHandler的核心功能是将http协议升级为ws协议 并保持长连接
  45. //是通过一个状态码 101
  46. .addLast("WebSocketServerProtocolHandler",new WebSocketServerProtocolHandler("/hello"))
  47. //自定义的handler做业务逻辑处理
  48. .addLast(new MyTextWebSocketFrameHandler());
  49. }
  50. });
  51. //启动服务器
  52. ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
  53. channelFuture.channel().closeFuture().sync();
  54. }finally {
  55. bossGroup.shutdownGracefully();
  56. workerGroup.shutdownGracefully();
  57. }
  58. }
  59. }
  60. package com.tech.netty.netty.websocket;
  61. import io.netty.channel.ChannelHandlerContext;
  62. import io.netty.channel.SimpleChannelInboundHandler;
  63. import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
  64. import java.time.LocalDateTime;
  65. /**
  66. * @author lw
  67. * @since 2021/8/20
  68. */
  69. //TextWebSocketFrame表示一个文本帧
  70. public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
  71. @Override
  72. protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
  73. System.out.println("服务端接收到消息"+msg.text());
  74. //回复消息
  75. ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间 "+ LocalDateTime.now()+" "+msg.text()));
  76. }
  77. //当web客户端连接后触发该方法
  78. @Override
  79. public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
  80. System.out.println("handlerAdded 被调用 "+ctx.channel().id().asLongText());
  81. System.out.println("handlerAdded 被调用 "+ctx.channel().id().asShortText());
  82. }
  83. @Override
  84. public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
  85. //id表示唯一 longText是唯一的 shortText不是惟一的
  86. System.out.println("handlerRemoved 被调用 "+ctx.channel().id().asLongText());
  87. System.out.println("handlerRemoved 被调用 "+ctx.channel().id().asShortText());
  88. }
  89. @Override
  90. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  91. System.out.println("异常发生 "+cause.getMessage());
  92. //关闭连接
  93. ctx.close();
  94. }
  95. }
  96. 客户端
  97. <!DOCTYPE html>
  98. <html lang="en">
  99. <head>
  100. <meta charset="UTF-8">
  101. <title>Title</title>
  102. </head>
  103. <body>
  104. <script>
  105. var socket;
  106. //判断当前浏览器是否支持websocket
  107. if(window.WebSocket) {
  108. //go on
  109. socket = new WebSocket("ws://localhost:7000/hello");
  110. //相当于channelReado, ev 收到服务器端回送的消息
  111. socket.onmessage = function (ev) {
  112. var rt = document.getElementById("responseText");
  113. rt.value = rt.value + "\n" + ev.data;
  114. }
  115. //相当于连接开启(感知到连接开启)
  116. socket.onopen = function (ev) {
  117. var rt = document.getElementById("responseText");
  118. rt.value = "连接开启了.."
  119. }
  120. //相当于连接关闭(感知到连接关闭)
  121. socket.onclose = function (ev) {
  122. var rt = document.getElementById("responseText");
  123. rt.value = rt.value + "\n" + "连接关闭了.."
  124. }
  125. } else {
  126. alert("当前浏览器不支持websocket")
  127. }
  128. //发送消息到服务器
  129. function send(message) {
  130. if(!window.socket) { //先判断socket是否创建好
  131. return;
  132. }
  133. if(socket.readyState == WebSocket.OPEN) {
  134. //通过socket 发送消息
  135. socket.send(message)
  136. } else {
  137. alert("连接没有开启");
  138. }
  139. }
  140. </script>
  141. <form onsubmit="return false">
  142. <textarea name="message" style="height: 300px; width: 300px"></textarea>
  143. <input type="button" value="发生消息" onclick="send(this.form.message.value)">
  144. <textarea id="responseText" style="height: 300px; width: 300px"></textarea>
  145. <input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
  146. </form>
  147. </body>
  148. </html>

程序运行后 测试效果如下:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpYW5nd2VubWFpbA_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,341人围观)

还没有评论,来说两句吧...

相关阅读

    相关 websocket 连接

    首先看一下什么是长连接,短连接 长连接的定义: 长连接 是一旦一个客户端登陆上服务器,其与服务器之间的连接就不关闭,不管他们之间进行了多少次交易,直到客户端退出登陆或

    相关 Netty 连接服务

    推送服务 还记得一年半前,做的一个项目需要用到 Android 推送服务。和 iOS 不同,Android 生态中没有统一的推送服务。Google 虽然有 [Google