netty+websocket模拟视频弹幕功能

很多视频播放都具备弹幕功能,A发了一个文字,B,C播放该视频若是开启了弹幕就能看到A发的。一开始挺好奇这个是怎么实现的,用JAVA是不是可以实现呢?答案肯定是可以的,最笨的用ajax 轮询。但是这种会给服务器造成很大压力,也浪费了服务器资源。netty 中 ChannelGroup可广播消息 netty+ websocket 则性能大大改善,废话不哔哔,下面直接贴代码了。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Netty WebSocket DEMO</title>
<script src="jquery.min.js"></script>
<style>
.tanmuContent {
    justify-content: space-between;
}
.headImg img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
}
.headImg {
    display: inline-block;
    width: 30px;
    height: 30px;
    background: red;
    border-radius: 41px;
}
</style>
</head>
<body>
    <script type="text/javascript">
        var socket;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            socket = new WebSocket("ws://localhost:8080/ws");
            //连接创建成功时被回调
            socket.onopen = function(event) {
              // alert("websocket创建成功!");
            };
            //收到服务端的消息时被回调
            socket.onmessage = function(event) {
                showMsg(event.data);
            };
            socket.onclose = function(event) {
                var ta = document.getElementById('responseText');
                ta.value = ta.value + "连接被关闭";
            };
        } else {
            alert("你的浏览器不支持!");
        }

        function send(message) {
            if (!window.WebSocket) {
                return;
            }
            if (socket.readyState == WebSocket.OPEN) {
                socket.send(message);
            } else {
                alert("连接没有开启.");
            }
        }
        function showMsg(msg){
        var id="div_"+new Date().getTime();
        var html='<div id="'+id+'" class="tanmuContent" style="position: absolute;"><span class="headImg"><img src="tanmuhead.jpg"></span>'+msg+'<div class="praiseBox"><span class="t-praise "></span></div></div>';
         var height=$(document).height();
         var width=$(document.body).width();
         html =$(html);
       var t = Math.floor(Math.random()*(height-1+1)+1);
       html.css("left",width*0.8+"px")
         html.css("top",t+"px")

         $("body").append(html);
         $("#"+id).animate({"left":-width},20000,function(){
          $("#"+id).remove();
          console.log("sss")
         });      


        }

    </script>
    <form onsubmit="return false;">
        <input type="text" name="message" value="Hello, World!"><input
            type="button" value="发送消息"
            onclick="send(this.form.message.value)">
    </form>
</body>
</html>
package com.xuyw;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.DefaultChannelGroup;
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.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WebSocketService2 {
    public void run(int port) throws Exception {  
        EventLoopGroup bossGroup = new NioEventLoopGroup();  
        EventLoopGroup workerGroup = new NioEventLoopGroup();  
        try {  
            final ServerBootstrap sb = new ServerBootstrap();  
            sb.group(bossGroup, workerGroup)  
             .channel(NioServerSocketChannel.class)  
             .childHandler(new ChannelInitializer<SocketChannel>() {  
                @Override  
                public void initChannel(final SocketChannel ch) throws Exception {  
                    ch.pipeline().addLast(  
                        new HttpResponseEncoder(),  
                        new HttpRequestDecoder(),  
                        new HttpObjectAggregator(65536),  
                        new WebSocketServerProtocolHandler("/ws"),  
                        new CustomTextFrameHandler());  
                }  
            }).option(ChannelOption.SO_BACKLOG, 65536)           
            .childOption(ChannelOption.SO_KEEPALIVE, true)  
            .childOption(ChannelOption.TCP_NODELAY, true);  
            //.childOption(ChannelOption.SO_BROADCAST, true);  
            //bootstrap.setOption("child.reuseAddress", true);        
            //bootstrap.setOption("child.tcpNoDelay", true);          
            //bootstrap.setOption("child.keepAlive", true);  

            final Channel ch = sb.bind(port).sync().channel();  
            System.out.println("Web socket server started at port " + port);  

            ch.closeFuture().sync();  
        } finally {  
            bossGroup.shutdownGracefully();  
            workerGroup.shutdownGracefully();  
        }  
    }  

    public static void main(String[] args) throws Exception {  
        int port;  
        if (args.length > 0) {  
            port = Integer.parseInt(args[0]);  
        } else {  
            port = 8080;  
        }  
        new WebSocketService2().run(port);  
    }  
}
package com.xuyw;

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;

public class CustomTextFrameHandler extends
        SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup recipients = new DefaultChannelGroup(
            "ChannelGroups", GlobalEventExecutor.INSTANCE);

    public CustomTextFrameHandler() {

    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx,
            TextWebSocketFrame frame) throws Exception {
        String request = frame.text();

        // ctx.channel().writeAndFlush(new
        // TextWebSocketFrame(request.toUpperCase()));
        System.out.println("size:" + recipients.size());
        recipients.writeAndFlush(new TextWebSocketFrame(request.toUpperCase()));

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        recipients.add(ctx.channel());
        System.out.println("connect:" + recipients.size());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        try {
            recipients.remove(ctx.channel());
            System.out.println("删除channel成功" + recipients.size());
        } catch (Exception ex) {
            System.out.println("删除channel失败" + ex.getMessage());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}

因为是随手写的demo,比较烂,凑合着看吧
这里写图片描述
本例基于netty 5.0.0.Alpha2

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
精通并发与 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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值