Netty中怎么实现websocket发消息

技术Netty中怎么实现websocket发消息本篇内容介绍了“Netty中怎么实现websocket发消息”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧

本篇内容介绍了"内蒂中怎么实现websocket发消息"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

1、pom文件

相关性

GroupDio。netty/GroupID

artifactIdnetty-all/artifactId

version4.1.25.Final/version

/dependency

2、index.html

!DOCTYPEhtml

超文本标记语言

metachartset=' utf-8 '/

标题/头衔

/head

身体

差异发送消息:/div

输入类型=' text ' id=' MSgcontent '/

inputtype='button'value='点我发送onclick='CHAT.chat()'/

差异接受消息:/div

divided=' receiveMsg '/div

脚本类型='应用程序/JavaScript '

窗户CHAT={ 0

socket:null,

init :函数(){ 0

如果(窗口WebSocket){ 0

聊天。socket=new WebSocket(' ws ://192)。168 .31 .160:8088/ws’);

聊天。插座。onopen=function(){ 0

console.log('连接建立成功.');

                  },
                  CHAT.socket.onclose = function() {
                     console.log("连接关闭...");
                  },
                  CHAT.socket.onerror = function() {
                     console.log("发生错误...");
                  },
                  CHAT.socket.onmessage = function(e) {
                     console.log("接受到消息:" + e.data);
                     var receiveMsg = document.getElementById("receiveMsg");
                     var html = receiveMsg.innerHTML;
                     receiveMsg.innerHTML = html + "<br/>" + e.data;
                  }
               } else {
                  alert("浏览器不支持websocket协议...");
               }
            },
            chat: function() {
               var msg = document.getElementById("msgContent");
               CHAT.socket.send(msg.value);
            }
         };
         CHAT.init();
      </script>
   </body>
</html>

3、main函数
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class WSServer {
   public static void main(String[] args) throws Exception {
      
      //定义一对线程组 
      // 主线程组, 用于接受客户端的连接,但是不做任何处理,跟老板一样,不做事      
      EventLoopGroup mainGroup = new NioEventLoopGroup();
      // 从线程组, 老板线程组会把任务丢给他,让手下线程组去做任务
      EventLoopGroup subGroup = new NioEventLoopGroup();
      
      try {
         // netty服务器的创建, ServerBootstrap 是一个启动类
         ServerBootstrap server = new ServerBootstrap();
         server.group(mainGroup, subGroup)    // 设置主从线程组
            .channel(NioServerSocketChannel.class)    // 设置nio的双向通道
            .childHandler(new WSServerInitialzer());  //// 子处理器,用于处理workerGroup
         
         // 启动server,并且设置8088为启动的端口号,同时启动方式为同步
         ChannelFuture future = server.bind(8088).sync();
         
         future.channel().closeFuture().sync();
      } finally {
         // 监听关闭的channel,设置位同步方式
         mainGroup.shutdownGracefully();
         subGroup.shutdownGracefully();
      }
   }
}
4、初始化类
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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.stream.ChunkedWriteHandler;
public class WSServerInitialzer extends ChannelInitializer<SocketChannel> {
   @Override
   protected void initChannel(SocketChannel ch) throws Exception {
      ChannelPipeline pipeline = ch.pipeline();
      
      // websocket 基于http协议,所以要有http编解码器
      pipeline.addLast(new HttpServerCodec());
      // 对写大数据流的支持 
      pipeline.addLast(new ChunkedWriteHandler());
      // 对httpMessage进行聚合,聚合成FullHttpRequest或FullHttpResponse
      // 几乎在netty中的编程,都会使用到此hanler
      pipeline.addLast(new HttpObjectAggregator(1024*64));
      
      // ====================== 以上是用于支持http协议    ======================
      
      // ====================== 以下是支持httpWebsocket ======================
      
      /**
       * websocket 服务器处理的协议,用于指定给客户端连接访问的路由 : /ws
       * 本handler会帮你处理一些繁重的复杂的事
       * 会帮你处理握手动作: handshaking(close, ping, pong) ping + pong = 心跳
       * 对于websocket来讲,都是以frames进行传输的,不同的数据类型对应的frames也不同
       */
      pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
      
      // 自定义的handler
      pipeline.addLast(new ChatHandler());
   }
}
5、助手类
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.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
/**
 * 
 * @Description: 处理消息的handler
 * TextWebSocketFrame: 在netty中,是用于为websocket专门处理文本的对象,frame是消息的载体
 */
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
   // 用于记录和管理所有客户端的channle
   private static ChannelGroup clients = 
         new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
   
   @Override
   protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) 
         throws Exception {
      // 获取客户端传输过来的消息
      String content = msg.text();
      System.out.println("接受到的数据:" + content);
      //类似于for循环
      clients.writeAndFlush(
            new TextWebSocketFrame(
                  "[服务器在]" + LocalDateTime.now() 
                  + "接受到消息, 消息为:" + content));
   }
   /**
    * 当客户端连接服务端之后(打开连接)
    * 获取客户端的channle,并且放到ChannelGroup中去进行管理
    */
   @Override
   public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
      clients.add(ctx.channel());
   }
   @Override
   public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
      // 当触发handlerRemoved,ChannelGroup会自动移除对应客户端的channel
//    clients.remove(ctx.channel());
      System.out.println("客户端断开,channle对应的长id为:" 
                     + ctx.channel().id().asLongText());
      System.out.println("客户端断开,channle对应的短id为:" 
                     + ctx.channel().id().asShortText());
   }
}
6、测试

运行index.html

发送消息,如下server端返回消息

Netty中怎么实现websocket发消息

“Netty中怎么实现websocket发消息”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/95858.html

(0)

相关推荐

  • word怎么看字数,没有word,怎样查文章字数

    技术word怎么看字数,没有word,怎样查文章字数安装一个UltraEdit之类的文本编辑工具,这类的软件可以被看作是记事本的加强版,但可以拥有比记事本更强得功能。比如你的问题,用UltraEdit统计字数的话,可以使

    生活 2021年10月26日
  • Oracle如何启用FRA和archivelog

    技术Oracle如何启用FRA和archivelog这篇文章给大家分享的是有关Oracle如何启用FRA和archivelog的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。Oracle启用FR

    攻略 2021年12月10日
  • arcsinx的不定积分,sinx的反函数的平方积分

    技术arcsinx的不定积分,sinx的反函数的平方积分sinx的反函数为arcsinx的不定积分:y=arcsinx或siny=x(x∈[-1,1])。arcsinx的平方的不定积分,写作:∫ arcsin²x dx分

    生活 2021年10月30日
  • C++引用的基本概念是什么

    技术C++引用的基本概念是什么本篇文章给大家分享的是有关C++引用的基本概念是什么,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。C++编程语言中有很多应用方

    攻略 2021年10月27日
  • mysql如何解决幻读(mysql2003错误如何解决)

    技术mysql 5.7如何解决忘记密码问题小编给大家分享一下mysql 5.7如何解决忘记密码问题,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧! mysql5.7忘记密码的解

    攻略 2021年12月16日
  • oracle静默安装的方法是什么

    技术oracle静默安装的方法是什么本篇内容介绍了“oracle静默安装的方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够

    攻略 2021年11月4日