springboot+netty+websocket实现消息推送(代码片段)

HelloWorld搬运工 HelloWorld搬运工     2022-11-29     793

关键词:

关于Netty

Netty 是一个利用 Java 的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的 API 的客户端/服务器框架。

Maven依赖

 

<dependencies>
 <!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
 <dependency>
  <groupId>io.netty</groupId>
  <artifactId>netty-all</artifactId>
  <version>4.1.36.Final</version>
 </dependency>

</dependencies>

SpringBootApplication

启动器中需要new一个NettyServer,并显式调用启动netty。

 

@SpringBootApplication
public class SpringCloudStudyDemoApplication 
 public static void main(String[] args) 
  SpringApplication.run(SpringCloudStudyDemoApplication.class,args);
  try 
   new NettyServer(12345).start();
   System.out.println("https://blog.csdn.net/moshowgame");
   System.out.println("http://127.0.0.1:6688/netty-websocket/index");
  catch(Exception e) 
   System.out.println("NettyServerError:"+e.getMessage());
  
 

NettyServer

启动的NettyServer,这里进行配置

 

/**
 * NettyServer Netty服务器配置
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
public class NettyServer 
    private final int port;
 
    public NettyServer(int port) 
        this.port = port;
    
 
    public void start() throws Exception 
        EventLoopGroup bossGroup = new NioEventLoopGroup();
 
        EventLoopGroup group = new NioEventLoopGroup();
        try 
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 1024);
            sb.group(group, bossGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class) // 指定使用的channel
                    .localAddress(this.port)// 绑定监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>()  // 绑定客户端连接时候触发操作
 
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception 
                            System.out.println("收到新连接");
                            //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            //以块的方式来写的处理器
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));
                            ch.pipeline().addLast(new MyWebSocketHandler());
                        
                    );
            ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
            System.out.println(NettyServer.class + " 启动正在监听: " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 关闭服务器通道
         finally 
            group.shutdownGracefully().sync(); // 释放线程池资源
            bossGroup.shutdownGracefully().sync();
        
    

MyChannelHandlerPool

通道组池,管理所有websocket连接

 

/**
 * MyChannelHandlerPool
 * 通道组池,管理所有websocket连接
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
public class MyChannelHandlerPool 

    public MyChannelHandlerPool()

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

MyWebSocketHandler

处理ws一下几种情况:

  • channelActive与客户端建立连接

  • channelInactive与客户端断开连接

  • channelRead0客户端发送消息处理

 

/**
 * NettyServer Netty服务器配置
 * @author zhengkai.blog.csdn.net
 * @date 2019-06-12
 */
public class NettyServer 
    private final int port;
 
    public NettyServer(int port) 
        this.port = port;
    
 
    public void start() throws Exception 
        EventLoopGroup bossGroup = new NioEventLoopGroup();
 
        EventLoopGroup group = new NioEventLoopGroup();
        try 
            ServerBootstrap sb = new ServerBootstrap();
            sb.option(ChannelOption.SO_BACKLOG, 1024);
            sb.group(group, bossGroup) // 绑定线程池
                    .channel(NioServerSocketChannel.class) // 指定使用的channel
                    .localAddress(this.port)// 绑定监听端口
                    .childHandler(new ChannelInitializer<SocketChannel>()  // 绑定客户端连接时候触发操作
 
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception 
                            System.out.println("收到新连接");
                            //websocket协议本身是基于http协议的,所以这边也要使用http解编码器
                            ch.pipeline().addLast(new HttpServerCodec());
                            //以块的方式来写的处理器
                            ch.pipeline().addLast(new ChunkedWriteHandler());
                            ch.pipeline().addLast(new HttpObjectAggregator(8192));
                            ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", "WebSocket", true, 65536 * 10));
                            ch.pipeline().addLast(new MyWebSocketHandler());
                        
                    );
            ChannelFuture cf = sb.bind().sync(); // 服务器异步创建绑定
            System.out.println(NettyServer.class + " 启动正在监听: " + cf.channel().localAddress());
            cf.channel().closeFuture().sync(); // 关闭服务器通道
         finally 
            group.shutdownGracefully().sync(); // 释放线程池资源
            bossGroup.shutdownGracefully().sync();
        
    

socket.html

主要是连接ws,发送消息,以及消息反馈

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Netty-Websocket</title>
    <script type="text/javascript">
        // by zhengkai.blog.csdn.net
        var socket;
        if(!window.WebSocket)
            window.WebSocket = window.MozWebSocket;
        
        if(window.WebSocket)
            socket = new WebSocket("ws://127.0.0.1:12345/ws");
            socket.onmessage = function(event)
                var ta = document.getElementById('responseText');
                ta.value += event.data+"\\r\\n";
            ;
            socket.onopen = function(event)
                var ta = document.getElementById('responseText');
                ta.value = "Netty-WebSocket服务器。。。。。。连接  \\r\\n";
            ;
            socket.onclose = function(event)
                var ta = document.getElementById('responseText');
                ta.value = "Netty-WebSocket服务器。。。。。。关闭 \\r\\n";
            ;
        else
            alert("您的浏览器不支持WebSocket协议!");
        
        function send(message)
            if(!window.WebSocket)return;
            if(socket.readyState == WebSocket.OPEN)
                socket.send(message);
            else
                alert("WebSocket 连接没有建立成功!");
            
 
        
 
    </script>
</head>
<body>
<form onSubmit="return false;">
    <label>ID</label><input type="text" name="uid" value="$uid!!" /> <br />
    <label>TEXT</label><input type="text" name="message" value="这里输入消息" /> <br />
    <br /> <input type="button" value="发送ws消息"
                  onClick="send(this.form.uid.value+':'+this.form.message.value)" />
    <hr color="black" />
    <h3>服务端返回的应答消息</h3>
    <textarea id="responseText" style="width: 1024px;height: 300px;"></textarea>
</form>
</body>
</html>

Controller

写好了html当然还需要一个controller来引导页面。

 

@RestController
public class IndexController 
 
 @GetMapping("/index")
 public ModelAndView  index()
  ModelAndView mav=new ModelAndView("socket");
  mav.addObject("uid", RandomUtil.randomNumbers(6));
  return mav;
 
 

效果演示

改造netty支持url参数

1.首先,调整一下加载handler的顺序,优先MyWebSocketHandlerWebSocketServerProtocolHandler之上。

 

ch.pipeline().addLast(new MyWebSocketHandler());
ch.pipeline().addLast(new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));

2.其次,改造MyWebSocketHandler 的channelRead方法,首次连接会是一个FullHttpRequest类型,可以通过FullHttpRequest.uri()获取完整ws的URL地址,之后接受信息的话,会是一个TextWebSocketFrame类型。

 

public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> 

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception 
        System.out.println("与客户端建立连接,通道开启!");

        //添加到channelGroup通道组
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
    

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception 
        System.out.println("与客户端断开连接,通道关闭!");
        //添加到channelGroup 通道组
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception 
        //首次连接是FullHttpRequest,处理参数 by zhengkai.blog.csdn.net
        if (null != msg && msg instanceof FullHttpRequest) 
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();

            Map paramMap=getUrlParams(uri);
            System.out.println("接收到的参数是:"+JSON.toJSONString(paramMap));
            //如果url包含参数,需要处理
            if(uri.contains("?"))
                String newUri=uri.substring(0,uri.indexOf("?"));
                System.out.println(newUri);
                request.setUri(newUri);
            

        else if(msg instanceof TextWebSocketFrame)
            //正常的TEXT消息类型
            TextWebSocketFrame frame=(TextWebSocketFrame)msg;
            System.out.println("客户端收到服务器数据:" +frame.text());
            sendAllMessage(frame.text());
        
        super.channelRead(ctx, msg);
    

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception 

    

    private void sendAllMessage(String message)
        //收到信息后,群发给所有channel
        MyChannelHandlerPool.channelGroup.writeAndFlush( new TextWebSocketFrame(message));
    

    private static Map getUrlParams(String url)
        Map<String,String> map = new HashMap<>();
        url = url.replace("?",";");
        if (!url.contains(";"))
            return map;
        
        if (url.split(";").length > 0)
            String[] arr = url.split(";")[1].split("&");
            for (String s : arr)
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key,value);
            
            return  map;

        else
            return map;
        
    

3.html中的ws地址也进行改造

 

socket = new WebSocket("ws://127.0.0.1:12345/ws?uid=666&gid=777");

4.改造后控制台输出情况

 

收到新连接
与客户端建立连接,通道开启!
接收到的参数是:"uid":"666","gid":"777"
/ws
客户端收到服务器数据:142531:这里输入消息
客户端收到服务器数据:142531:这里输入消息
客户端收到服务器数据:142531:这里输入消息

failed: WebSocket opening handshake timed out

听说是ssl wss的情况下才会出现,来自 @around-gao 的解决方法:

MyWebSocketHandlerWebSocketServerProtocolHandler调下顺序就好了。

#springboot集成netty(代码片段)

SpringBoot集成Netty文章目录SpringBoot集成Netty背景描述Netty与SpringBoot整合关注点Netty组件Bootstrap、ServerBootstrapChannelEventLoop、EventLoopGroupChannelHandlerChannelPipelineByteBufPom依赖Yml配置整合Netty步骤服务端客户端背景描述如果需要在SpringBoot开... 查看详情

springboot+netty

<!--netty依赖springboot2.x自动导入版本--><dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId></dependency>publicclassAllServiceApplicationimplementsCommandLineRunnerprivateLoggerlogger=LoggerFactory.getLogger(this.getClass());pub... 查看详情

springboot启动成功后启动netty服务端

springbootnettyspringboot启动成功后启动netty服务端springbootnettyspringboot启动成功后启动netty服务端 查看详情

springboot集成netty实现udpserver(代码片段)

注:ApplicationRunner接口是在容器启动成功后的最后一步回调(类似开机自启动)。UDPServerpackagecom.vmware.vCenterEvent.netty;importio.netty.bootstrap.Bootstrap;importio.netty.channel.*;importio.netty.channel.nio.NioEventLoopGroup;im 查看详情

360四面:说说springboot程序启动中netty异步架构的原理!

...使用了Netty。今天,我们来看看Netty的基本架构和原理。SpringBoot实战学习笔记Netty的特点与NIONetty是一个异步的、基于事件驱动的网络应用框架,它可以用来开发高性能服务端和客户端。以前编写网络调用程序的时候,我们都会在... 查看详情

禁用 Springboot RSocket 项目的“默认”Netty 端口

】禁用SpringbootRSocket项目的“默认”Netty端口【英文标题】:Disablethe"default"NettyportforaSpringbootRSocketproject【发布时间】:2021-03-1905:11:45【问题描述】:请教关于SpringbootRSocket项目的问题。我正在构建一个仅使用SpringbootRSocket... 查看详情

springboot+netty+websocket实现消息推送(代码片段)

关于NettyNetty是一个利用Java的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的API的客户端/服务器框架。Maven依赖<dependencies> <!-- https://mvnrepository.com/artifact/io.netty/netty-all --> <dependency>  <groupId&g 查看详情

netty实战项目:springboot程序的聊天程序

1.背景主要是想使用这个聊天程序,做netty的实战项目,最终实现和钉钉或者QQ相似的功能,或者是锻炼一下自己的netty知识。希望看到的一起加入一起完善。2.说明2.1git地址仓库地址:https://github.com/lccbiluox2/InChat.git分支:我实在... 查看详情

netty实战项目:springboot程序的聊天程序

1.背景主要是想使用这个聊天程序,做netty的实战项目,最终实现和钉钉或者QQ相似的功能,或者是锻炼一下自己的netty知识。希望看到的一起加入一起完善。2.说明2.1git地址仓库地址:https://github.com/lccbiluox2/InChat.git分支:我实在... 查看详情

springboot+netty+websocket实现消息推送(代码片段)

springboot和netty,websocket实现消息主动推送注:本文转自:https://mp.weixin.qq.com/s/YWjGdz-4PzOCDfEt4GPoew1.关于NettyNetty是一个利用Java的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的API的客户端/服务器框架。2.Maven依赖<depe... 查看详情

大屏的接口开发二:基于springboot的netty数据推送(代码片段)

...章是继个人大屏接口方法系列:大屏的接口开发一:基于SpringBoot的webSocket数据推送之后的第二篇文章,也是实现大屏项目的服务端主动推送数据到前端的一个服务工具类,其相关的业务流程也是跟第一版有很大的相似之处1.Spring... 查看详情

大屏的接口开发二:基于springboot的netty数据推送(代码片段)

...章是继个人大屏接口方法系列:大屏的接口开发一:基于SpringBoot的webSocket数据推送之后的第二篇文章,也是实现大屏项目的服务端主动推送数据到前端的一个服务工具类,其相关的业务流程也是跟第一版有很大的相似之处1.Spring... 查看详情

springboot+netty+websocket实现消息推送(代码片段)

点击关注公众号,实用技术文章及时了解关于NettyNetty是一个利用Java的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的API的客户端/服务器框架。Maven依赖<dependencies> <!-- https://mvnrepository.com/artifact/io.net... 查看详情

springboot+netty+websocket实现消息推送(代码片段)

点击关注公众号,实用技术文章及时了解关于NettyNetty是一个利用Java的高级网络的能力,隐藏其背后的复杂性而提供一个易于使用的API的客户端/服务器框架。Maven依赖<dependencies> <!-- https://mvnrepository.com/artifact/io.net... 查看详情

基于netty和springboot实现一个轻量级rpc框架-client篇(代码片段)

前提前置文章:《基于Netty和SpringBoot实现一个轻量级RPC框架-协议篇》《基于Netty和SpringBoot实现一个轻量级RPC框架-Server篇》前一篇文章相对简略地介绍了RPC服务端的编写,而这篇博文最要介绍服务端(Client)的实现。RPC调用一般... 查看详情

springboot集成netty框架(物联网tcp连接,只服务端)(代码片段)

Maven<dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>5.0.0.Alpha2</version></dependency>NettyServerBootStrap.java&# 查看详情

springboot集成netty-socket.io

参考技术Anetty-socekt.IO官网socket.io是一个netty.socketnode版的java实现版,其性能优于webSocket等socket技术,socket.io有nameSpace等,分区方式,比较灵活。originHost为socket客户端的地址,serverHost请使用ip,lz在使用过程中尝试过使用localhost,... 查看详情

springboot+netty+websocket实现消息推送(代码片段)

...n>4.1.36.Final</version> </dependency></dependencies>SpringBootApplication启动器中需要new一个NettyServer,并显式调用启动netty。@SpringBootApplicationpublic class SpringCloudStudyDemoApplication  public static void main(String[] args)   Sprin... 查看详情