最近项目要实现视频播放时做弹幕和评论滚动,使用flash做sockt编程不会,就想到使用服务器消息推送做,翻找资料发现使用html5的websocket可以实现,但是ie8是不支持websocket的,最终确定使用dwr3做消息推送,普通的dwr3做消息推送会把消息推送到所有打开的页面,这样针对某一个视频的评论就会弹出到其他的视频中去,实现每个视频弹出各自的评论,就需要做dwr3的消息推送做过滤处理,经过一天的研究终于搞定了

贴出完整的代码demo

1 使用dwr3的web.xml的配置

<servlet-name>dwr-invoker</servlet-name>
    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
    
        <init-param>
         <param-name>fileUploadMaxBytes</param-name>
         <param-value>25000</param-value>
        </init-param>
        
        <!-- This should NEVER be present in live -->
        <init-param>
          <param-name>debug</param-name>
          <param-value>true</param-value>
        </init-param>
      
        <init-param>
          <param-name>accessLogLevel</param-name>
          <param-value>runtimeexception</param-value>
        </init-param>
        
        <!-- Remove this unless you want to use active reverse ajax -->
        <init-param>
          <param-name>activeReverseAjaxEnabled</param-name>
          <param-value>true</param-value>
        </init-param>
    
        <!-- By default DWR creates application scope objects when they are first
        used. This creates them when the app-server is started -->
        <init-param>
          <param-name>initApplicationScopeCreatorsAtStartup</param-name>
          <param-value>true</param-value>
        </init-param>
    
        <!-- WARNING: allowing JSON-RPC connections bypasses much of the security
        protection that DWR gives you. Take this out if security is important -->
        <init-param>
          <param-name>jsonRpcEnabled</param-name>
          <param-value>true</param-value>
        </init-param>
    
        <!-- WARNING: allowing JSONP connections bypasses much of the security
        protection that DWR gives you. Take this out if security is important -->
        <init-param>
          <param-name>jsonpEnabled</param-name>
          <param-value>true</param-value>
        </init-param>
    
        <!-- data: URLs are good for small images, but are slower, and could OOM for
        larger images. Leave this out (or keep 'false') for anything but small images -->
        <init-param>
          <param-name>preferDataUrlSchema</param-name>
          <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>

2 dwr.ml的配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd">
<dwr>
    <allow>
        <create creator="new" scope="application">
          <param name="class" value="com.example.dwr.reverseajax.JavascriptChat"/>
        </create>
        <create creator="new" scope="application">
          <param name="class" value="com.example.dwr.reverseajax.JavaChat"/>
        </create>
        <convert converter="bean" match="com.example.dwr.reverseajax.Message"/>
   </allow>
</dwr>
3 项目中使用了strust2,需要配置一个属性以便strust2放过dwr的请求

<constant name="struts.action.excludePattern" value="/dwr/*" />

4 java代码

(1)用于接收消息和处理消息的java文件

package com.example.dwr.reverseajax;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ScriptSessions;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import com.jovision.modelBean.LoginInfo;

/**
 *
 * @author liuhailong
 *
 */
public class JavascriptChat
{
   
    public void addMessage(String text,final String oid)
    {
        String mess = text;
        WebContext wc = WebContextFactory.get();
        wc.getScriptSession().setAttribute("oid", oid);
        LoginInfo loginInfo = (LoginInfo) wc.getSession().getAttribute("loginInfo");
        if (loginInfo != null) {
            mess = loginInfo.getAccount() + "说:" + mess;
        }else{
            mess = "游客说:" + mess;
        }
        if(!map.containsKey(oid)){
            LinkedList<Message> list = new LinkedList<Message>();
            map.put(oid, list);
        }
        final LinkedList<Message> messages = map.get(oid);
        if (text != null && text.trim().length() > 0)
        {
            messages.addFirst(new Message(mess));
            while (messages.size() > 10)
            {
                messages.removeLast();
            }
        }
        //过滤器
        ScriptSessionFilter filter = new ScriptSessionFilter() {
            public boolean match(ScriptSession scriptSession) {
                 String tag = (String)scriptSession.getAttribute("oid");
                 return oid.equals(tag);
            }
        };
        //执行方法
        Runnable run = new Runnable(){
              public void run() {
                  ScriptSessions.addFunctionCall("receiveMessages", messages);
             }
        };
        //发送消息
        Browser.withCurrentPageFiltered(filter,run);
    }

/*
     * 存储消息的map对象
     */
    private final Map<String,LinkedList<Message>> map = new HashMap<String,LinkedList<Message>>();
    
}

(2)消息对象

package com.example.dwr.reverseajax;

/**
 * @author liuhailong
 */
public class Message
{
    /**
     * @param newtext the new message text
     */
    public Message(String newtext)
    {
        text = newtext;

if (text.length() > 256)
        {
            text = text.substring(0, 256);
        }
    }

/**
     * @return the message id
     */
    public long getId()
    {
        return id;
    }

/**
     * @return the message itself
     */
    public String getText()
    {
        return text;
    }

/**
     * When the message was created
     */
    private long id = System.currentTimeMillis();

/**
     * The text of the message
     */
    private String text;
}

5 用于消息弹出的jsp页面

<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="cn" lang="cn">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Simple DWR Chat Version 3.0</title>
  <script type='text/javascript' src='../dwr/engine.js'> </script>
  <script type='text/javascript' src='../dwr/interface/JavascriptChat.js'> </script>
  <script type='text/javascript' src='../dwr/util.js'> </script>
  <script type="text/javascript" src='javascript-chat.js'> </script>
</head>
<body οnlοad="init();Tabs.init('tabList', 'tabContents');">
<div id="tabContents">
  <div id="demoDiv">
    <div id="chatlog" style="height:400px;overflow-y:auto"></div>
    <p>
          评论:
      <input id="text" οnkeypress="dwr.util.onReturn(event, sendMessage)"/>
      <input type="button" value="发送" οnclick="sendMessage()"/>
    </p>
  </div>
</div>
</body>
</html>

6 使用的javescript脚本文件代码

function init() {
  dwr.engine.setActiveReverseAjax(true);
}

function sendMessage() {
  var text = dwr.util.getValue("text");
  var oid = window.parent.document.getElementById('oid').value;
  dwr.util.setValue("text", "");
  JavascriptChat.addMessage(text,oid);
}

function receiveMessages(messages) {
  var chatlog = "";
  for (var data in messages) {
    chatlog = "<div>" + dwr.util.escapeHtml(messages[data].text) + "</div>" + chatlog;
  }
  dwr.util.setValue("chatlog", chatlog, { escapeHtml:false });
}
做该功能时观看了网上一位比较了解dwr的人员的博客 网页地址:http://www.kankanews.com/ICkengine/archives/82552.shtml 点击打开链接
使用这种方式能够实现消息弹幕 缺点是比较消耗服务器资源,希望还有更好的办法提供

使用dwr3.0实现服务端向浏览器做消息推送,做滚动评论或弹幕效果,而且根据视频id做推送消息拦截功能相关推荐

  1. vue3.0对服务端进行渲染

    vue3.0支持服务端渲染.Vue支持将组件在服务端直接渲染成HTML字符串,作为服务端响应返回给浏览器,最后在浏览器端将静态的HTML"激活"(hydrate) 为能够交互的客户 ...

  2. 导出Excel功能-从服务端到浏览器的简单处理

    导出Excel功能 从服务端到浏览器的简单处理, 仅供参考 服务端定义一个导出功能的关键代码 Java 定义一个export的功能函数,以下为关键代码(接口中的一部分处理逻辑): @Override ...

  3. 使用 Vue 2.0 实现服务端渲染的 HackerNews

    Vue 2.0 支持服务端渲染 (SSR),并且是流式的,可以做组件级的缓存,这使得极速渲染成为可能.同时, 和 2.0 也都能够配合 SSR 提供同构路由和客户端 state hydration.v ...

  4. 热血江湖服务端 linux,热血江湖V2.0商业服务端百宝阁 GM工具+客户端+架设教程

    热血江湖V2.0商业服务端百宝阁 GM工具+客户端+架设教程 本人没有测试过!!!本人没有测试过!!!本人没有测试过!!! 可升级120级,个别服升150级8转 爆率低 特别是强化石 强化石可以叠加 ...

  5. php热血江湖怎么安装,端游【热血江湖】V2.0商业服务端百宝阁 GM工具+客户端+架设教程...

    热血江湖V2.0商业服务端百宝阁 GM工具+客户端+架设教程 本人没有测试过!!!本人没有测试过!!!本人没有测试过!!! 可升级120级,个别服升150级8转 爆率低 特别是强化石 强化石可以叠加 ...

  6. 西部数据php一键安装,【贪狼某道1.60特色服务端】WD某道1.60一键安装客户端带GM管理工具[附视频搭建教程]...

    [贪狼某道1.60特色服务端]WD某道1.60一键安装客户端带GM管理工具[附视频搭建教程] 出生就进传送阵 然后地上宝箱随便点就125了 你会看到北极仙翁 前面传送阵出来就能看到他哥哥南极仙翁 领取 ...

  7. vue服务端渲染浏览器端缓存(keep-alive)

    在使用服务器端渲染时,除了服务端的接口缓存.页面缓存.组建缓存等,浏览器端也避免不了要使用缓存,减少页面的重绘. 这时候我们就会想到vue的keep-alive,接下来我们说一下keep-alive的 ...

  8. swift perfect mysql_Swift3.0服务端开发(一) 完整示例概述及Perfect环境搭建与配置(服务端+iOS端)...

    本篇博客算是一个开头,接下来会持续更新使用Swift3.0开发服务端相关的博客.当然,我们使用目前使用Swift开发服务端较为成熟的框架Perfect来实现.Perfect框架是加拿大一个创业团队开发 ...

  9. springboot实现SSE服务端主动向客户端推送数据,java服务端向客户端推送数据,kotlin模拟客户端向服务端推送数据

    SSE服务端推送 服务器向浏览器推送信息,除了 WebSocket,还有一种方法:Server-Sent Events(以下简称 SSE).本文介绍它的用法. 在很多业务场景中,会涉及到服务端向客户端 ...

最新文章

  1. C#之windows桌面软件第九课:汉字串口助手
  2. 图:BFS/DFS java实现
  3. [MATLAB粒子模拟笔记]归一化输入系数
  4. mfc 子窗体任何消息都不触发_winform让窗体一直显示在桌面上以及FindWindow
  5. Linux MySQL 忘记root 密码
  6. Struts2显示double价格格式0.00
  7. Python实例讲解 -- 操作数据库 附mysqldb win32 py2.7下载
  8. MySQL中GTID的几个限制和解决方案(r13笔记第21天)
  9. 网络(11)-什么是RestFul风格?
  10. sp+Ssh+Mysql实现的简单的企业物资信息管理
  11. oracle,sqlserver,mysql区别
  12. 神界计算机丢失msvcp120.dll,win8 msvcp120.dll丢失怎样修复?计算机中丢失msvcp120.dll处理办法...
  13. android av和hdmi输出切换代码,AV转HDMI转换器有用吗?
  14. 怎么运行java程序_怎么运行java程序?运行java程序的一般步骤?
  15. java碰碰球历险记下载_幼儿园玩球教案碰碰球.doc
  16. Paradoxes of particularity: Caribbean literary imaginaries【翻译】
  17. Windows 好用的软件安装清单 持续更新
  18. iOS开发 UIBezierPath曲线动画
  19. 2022年河北省高职单招(综合素质)考试冲刺试题及答案
  20. HTML表格自动排序

热门文章

  1. spark Word2Vec+LSH相似文本推荐(scala)
  2. JIEMI人体美化技术-职业重要
  3. vue暴露一个就js 以及引入详解
  4. svm算法python实现_手把手教你python实现SVM算法
  5. php无法移动上传文件,PHP警告:move_uploaded_file()无法移动
  6. python用程序说爱你,抖音表白程序Python版,明人不说暗话,我喜欢你
  7. 【Hive---02】hive概述『 what | 优缺点 | 架构 | Hivevs MySQL』
  8. android 高度动画,android-如何使用动画扩展布局高度?
  9. 使用adb时出现Permission denied的解决办法
  10. Failed to execute goal on project