评论功能+websocket自动更新

代码存根,作为文档保存。

1、comment.jsp 页面

<div class="row">
    <div class="col-md-12 col-sm-12 col-xs-12">
        <div class="report_comment">
            <p class="bt_report"><i class="iconfont icon-pinglun"></i><font>发表评论</font></p>
            <div class="report_text">
                <div class="pull-left width10 loginPhoto">
                    <img alt="" class="img-circle" src="">
                </div>
                <div class="pull-left chearfix width_calc90">
                    <textarea rows="4" cols="5" class="form-control" id="comment" placeholder="来说两句吧…" style="resize:none;"></textarea>
                </div>
                <div class="text-right btn-report"><button class="btn btn-default btn-box-custom" onclick="sendComment()">发表</button></div>
            </div>
        </div>

        <div class="all_commentList">
            <p>全部评论 <font style="font-size: 14px;color: #888;" id="commentSum"></font></p>

            <table class="table" id="commentTable">


            </table>

            <table style="width: 100%">
                <tr>
                    <td align="center">
                        <ul class="pagination" id="ulpage">

                        </ul>
                    </td>
                </tr>
            </table>

            <!-- <div class="row">
                <div class="col-md-12 col-sm-12 col-xs-12">
                    <div class="show_more_comments">
                        <center>查看更多评论</center>
                    </div>
                </div>
            </div> -->

        </div>

    </div>
</div>


<script src="${ctxStatic}/web/js/comment/comment.js"
        type="text/javascript"></script>

    <script type="text/javascript">
        //与服务器websocket连接
        $(document).ready( function() {
            var websocket = null;

            //判断当前浏览器是否支持WebSocket  
            if ('WebSocket' in window) {
                websocket = new WebSocket(
                        "${fns:getConfig('PUBCOMMENTWEBSOCKET')}");
            } else {
                showTip("未提供websocket服务!");
            }

            //连接发生错误的回调方法  
            websocket.onerror = function() {
                console.log("error");
                showTip("websocket连接失败,不能即时更新评论信息!");
            };

            //连接成功建立的回调方法  
            websocket.onopen = function(event) {
                websocket.send("commentId: "+articleId+",loginId: " + _uid); //将连接信息与登陆账号绑定
            }

            //接收到消息的回调方法  
            websocket.onmessage = function(event) {
                var serverMessage = event.data;

                if (serverMessage.indexOf('updatePubComment-') != -1) {
                    data = serverMessage.replace("updatePubComment-", "");
                    if (data != null && data != "") {
                        data = JSON.parse(data);
                        var html = discussItem(data);
                        $(".all_commentList .table").prepend(html);
                        $("#comment").val("");
                    }

                } else if (serverMessage.indexOf('updateReplyComment-') != -1) {
                    var updateReplyComment = serverMessage.substring(0, serverMessage.indexOf("*"));
                    var id = serverMessage.substring(serverMessage.lastIndexOf("*") + 1);

                    id = id.replace("id-", "");
                    data = updateReplyComment.replace("updateReplyComment-", "");
                    if (data != null && data != "") {
                        data = JSON.parse(data);
                        var html = replyItem(data);
                        $(".all_commentList #conListShow"+id+" #"+id+" #replyData"+id).prepend(html);
                        $("#repleText").val("");
                    }
                }

            }

            //连接关闭的回调方法  
            websocket.onclose = function() {
                console.log("close");
            }

            //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。  
            window.onbeforeunload = function() {
                websocket.close();
            }

            //关闭连接  
            function closeWebSocket() {
                websocket.close();
            }

        })
    </script>

2、comment.js

var pageNo = 1;
var pageSize = 5; 

var pageNo_article = 1;
var pageSize_article = 5; 

var nodeId = "";
$(function(){
    //重新定义分页时页面绑定事件;
    reBind = function() {
        pageNo = jumpIndex;
        discussData();
    }

    //重新定义分页时页面绑定事件;
    reBind_article = function() {       
        pageNo_article = jumpIndex_article;
        replyDiscuss(nodeId);
    }

    // 进入页面查询
    bindStartSearch();  

})

function bindStartSearch(){
    // 查詢列表
    discussData();
    paging(pageSize, pageNo);
}

//写成公共方法
function pageRes(){
    pageNo_article = 1;
    replyDiscuss(nodeId);
    paging_article(pageSize_article, pageNo_article, 'ulpageChild', nodeId);
}

// 显示评论
function discussData() {
    var searchData={
        parentId : articleId,
        category: "文章评论",
        pageSize: pageSize,
        pageNo: pageNo
    };
    doAjax(ctx + "/zone/PubCommentAPI/discussData", searchData, false, "bindList(data)", "");
}
function bindList(data){
    $("#commentTable").empty();
    rowcount =data.rowcount;
    data = data.rows;
    for ( var i in data)
    {
        var html = discussItem (data[i]);
        $("#commentTable").append(html);
    }
}

// 发表评论
function sendComment() {
    // 判断用户是否登录
    if (fnsGetUser == '') {
        layer.alert("您还没有登录,请登录后再进行操作!", {
            icon : 0,
            title : '操作失败',
            offset : "350px"
        });
        return;
    } else {
        var comment = $("#comment").val();
        if (comment != null && comment != "") {
            var zoneDiscussData = {
                "nodeId" : articleId,
                "commentValue" : comment,
                "category" : '文章评论',
                "userId" : _uid,
                "identify" : "zone_wzpl"
            };
            doAjax(ctx + "/zone/PubCommentAPI/addZoneDiscuss", zoneDiscussData, false, "returnZoneDiscussData(data)", "");
        } else {
            layer.msg("评论内容不能为空!");
        }
    }
}

function returnZoneDiscussData(data) {
    $("#comment").val("");
}

// 发表返回
function discussItem (item)
{
    var html = "<tr name="+item.id+" data-show='hide'>";
    html += "<td class='itemTd'>";
    html += "<div class='comment-show-con clearfix'>";
    html += "<div class='comment-show-con-img pull-left'>";
    html += "<img src="+item.photo+" alt=''>";
    html += "</div>";
    html += "<div class='comment-show-con-list pull-left clearfix' id=conListShow"+item.id+">";
    html += "<div class='pl-text clearfix' id="+item.id+">";
    html += "<span href='#' class='comment-size-name'>"+item.userName+"</span>";
    html += "<div class='date-dz-right pull-right comment-pl-block'>";
    html += "<a href='javascript:;' class='date-dz-pl pl-hf pull-left' onclick=\"replyComment('"+item.id+"')\">评论("+item.commentSum+")</a>";
    html += "<a href='javascript:;' class='removeBlock' onclick=\"deleteComment('"+item.id+"', '"+item.processNodeId+"')\">删除</a>";
    html += "</div>";
    html += "<div class='comment-content'>" + item.commentValue + "</div>";
    html += "<span class='date-dz-left pull-left comment-time'>" + DateHandle(item.commentTime) + "</span>";

    html += "<div id='reply"+item.id+"'>";
    html += "</div>";

    html += "<div id='replyData"+item.id+"'>";

    html += "<table style='width: 100%;display: none;'>";
    html += "<tr>";
    html += "<td align='center'>";
    html += "<ul class='pagination' id='ulpageChild"+item.id+"'>";
    html += "</ul>";
    html += "</td>";
    html += "</tr>";
    html += "</table>";
    html += "</div>";

    html += "</div>";

    html += "</div>";
    html += "</div>";
    html += "</td>";
    html += "</tr>";

    return html;
}

// 回复返回
function replyItem(item) {

    var html = "<div class='reply_comment' name="+item.id+" style='display: inlink-block;'>";
    html += "<div class='pull-left reply_comment_img'>";
    html += "<img src="+item.photo+" alt=''>";
    html += "</div>";
    html += "<div class='pull-left reply_comment_right'>";
    html += "<p class='box_reply_comment'>";
    html += "<font class='box_reply_color'>"+item.userName+" &nbsp;回复:</font>" +
            "" + item.commentValue + "<span class='reply_del'><a onclick=\"deleteComment('"+item.id+"', '"+item.processNodeId+"')\">删除</a></span>";
    html += "</p>";
    html += "<p class='reply_time'>" + DateHandle(item.commentTime) + "</p>";
    html += "</div>";
    html += "</div>";

    return html;
}


function DateHandle(objDate) {  
    var datetime = new Date(objDate);

    var month = datetime.getMonth()+1;   //getMonth()返回的月份是从0开始的,还要加1     
    var date = datetime.getDate()-1;     
    var hours = datetime.getHours()+10;     
    var minutes = datetime.getMinutes();  
    if (parseInt(minutes) < 10) {
        minutes = "0" + minutes;
    } else {
        minutes = minutes;
    }
    var date = month+"-"+date+" "+hours+":"+minutes;  
    return date;   
}  

// 点击回复按钮
function replyComment(id) {
    nodeId = id;
    var attr = $("tr[name='"+id+"']").attr("data-show");
    if(attr == "hide") {
        $("tr[name='"+id+"']").attr("data-show", "show");

        $(".reply").hide();
        $("tr[name='"+id+"'] table").show();
        // 回复框
        var html = "<div class='date-dz reply' name='"+id+"'>";
        html += "<div class='date-dz'>";
        html += "<div class='flex-text-wrap'>";
        html += "<textarea rows='3' cols='5' class='form-control ' id='repleText' placeholder='我也说一句' style='resize:none;'></textarea>";
        html += "</div>";
        html += "<div class='text-right btn-reply'><button class='btn btn-default btn-box-custom-radius ' onclick=\"replySubmit('"+id+"')\">发表</button></div>";
        html += "</div>";

        $("tr[name='" + id + "'] #conListShow"+id+" #"+id + " #reply"+id).append(html);

        pageRes();
    } else {
        $(".reply").hide();
        $(".reply_comment").hide();
        $("tr[name='"+id+"']").attr("data-show", "hide");
        $("tr[name='"+id+"'] table").hide();
    }

}

function replyDiscuss(nodeId) {
    var replyData = {
        parentId : nodeId,
        category: "文章评论",
        pageSize: pageSize_article,
        pageNo: pageNo_article
    };
    doAjax(ctx + "/zone/PubCommentAPI/discussData", replyData, false, "replyDiscussData(data, '"+nodeId+"')", "");
}


function replyDiscussData(data, id) {
    $(".all_commentList #conListShow"+id+" #"+id+" #replyData"+id + " .reply_comment").remove();
    // 记录数
    rowcount_article = data.rowcount;
    data = data.rows;
    for ( var i in data)
    {
        var html = replyItem (data[i]);
        $(".all_commentList #conListShow"+id+" #"+id+" #replyData"+id).prepend(html);
    }
}


// 发表回复
function replySubmit(id) {
    // 判断用户是否登录
    if (fnsGetUser == '') {
        layer.alert("您还没有登录,请登录后再进行操作!", {
            icon : 0,
            title : '操作失败',
            offset : "350px"
        });
        return;
    } else {
        var replyVal = $("div[name='"+id+"']").find("#repleText").val();
        if (replyVal != null && replyVal != "") {
            var replyDiscussData = {
                "nodeId" : id,
                "commentValue" : replyVal,
                "category" : '文章评论',
                "userId" : _uid,
                "identify" : "zone_wzpl"
            };
            doAjax(ctx + "/zone/PubCommentAPI/addZoneDiscuss", replyDiscussData, false, "returnZoneDiscussData(data)", "");
        } else {
            layer.msg("回复内容不能为空!");
        }
    }

}

function returnZoneDiscussData(data) {
    $("#repleText").val("");
}


// 删除评论
function deleteComment(id, ComId) {
    layer.confirm ('确认要删除该评论吗?',
    {
        icon : 3,
        title : '系统提示',
        offset : "350px"
    }, function (index)
    {
        var delData = {
            "id" : id,
            "identify" : "zone_wzpl",
            "category" : '文章评论',
            "ComId" : ComId
        };
        doAjax(ctx + '/zone/PubCommentAPI/DelComment', delData, false, "returnDelData(data, '"+id+"')", "");
    });
}
// 删除评论,返回参数
function returnDelData(data, id) {
    if (data.code == "1")
    {
        layer.msg ("删除成功!", {icon: 1, offset : "350px"});
        if(data.parentId == "0") {
            $ ("tr[name='" + id + "']").remove ();
        } else {
            $ ("div[name='" + id + "']").remove ();
        }

    }
}

paging(pageSize, pageNo); 自己写的分页,具体见:

websocket 客户端:
这里写图片描述

3、PubCommentWebSocketClient.java

package com.jeeplus.modules.websocket;

import java.net.URI;
import java.net.URISyntaxException;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import com.jeeplus.common.config.Global;

public class PubCommentWebSocketClient extends WebSocketClient {


    private static PubCommentWebSocketClient client;  

    public static synchronized PubCommentWebSocketClient getInstance() {  
        if (client == null) {  
            String webSocketServer = Global.getConfig("PUBCOMMENTWEBSOCKET");
            URI serverURI = null;
            try {
                serverURI = new URI(webSocketServer);
                client = new PubCommentWebSocketClient(serverURI);  
                client.connectBlocking();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }  
        return client;  
    }  
    private PubCommentWebSocketClient(URI serverURI) {
        super(serverURI);
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        System.out.println("评论的WebSocketServer已被关闭!");
        client = null;
    }

    @Override
    public void onError(Exception arg0) {
        // TODO Auto-generated me2thod stub
        System.out.println("评论的WebSocketServer发生错误!");
        client = null;

    }

    @Override
    public void onMessage(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onOpen(ServerHandshake arg0) {
        // TODO Auto-generated method stub

    }

}

4、PubCommentWebSocketThread.java

package com.jeeplus.modules.websocket;

public class PubCommentWebSocketThread implements Runnable {

    private String id;
    private String identify;
    private String category;
    private String userId;

    @Override
    public void run() {
        sendWebSocketMessage(id, identify, category, userId);
    }

    public void sendWebSocketMessage(String id, String identify, String category, String userId) {
        PubCommentWebSocketClient client = PubCommentWebSocketClient.getInstance();
        if ("zxyt".equals(identify)) {
            client.send("zxytId:" + id);
        } else if ("comment".equals(identify)) {
            client.send("SendComId:" + id + "," + category);
        } else if ("zone_wzpl".equals(identify)) {
            client.send("zoneArtileId:" + id + "," + category + "," + userId);
        }

    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getIdentify() {
        return identify;
    }

    public void setIdentify(String identify) {
        this.identify = identify;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public PubCommentWebSocketThread(String id, String identify, String category, String userId) {
        super();
        this.id = id;
        this.identify = identify;
        this.category = category;
        this.userId = userId;
    }


}

5、xx.properties 配置中增加端口

这里写图片描述
当用户点击发送按钮后,在完成后增加

new Thread(new PubCommentWebSocketThread(pubc.getId(), identify, pubcom.getCategory(), pubcom.getUserId())).start();

然后客户端发送请求到服务端
这里写图片描述

6、WebSockertFilter.java

/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.websocket;

import java.io.IOException;
import java.net.UnknownHostException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.jeeplus.modules.websocket.homework.HomeworkServer;
import com.jeeplus.modules.websocket.pubComment.PubCommentServer;

public class WebSockertFilter implements Filter{

    /**
     * 初始化
     */
    public void init(FilterConfig fc) throws ServletException {
        this.startWebsocketChatServer();
    }

    /**
     * 启动websocket:
     * 1.待完成作业
     */
    public void startWebsocketChatServer(){
        PubCommentServer pc;
        HomeworkServer s;
        try {
            s = new HomeworkServer(7788);
            pc = new PubCommentServer(8899);
            s.start();
            pc.start();
            System.out.println( "websocket评论启动,端口" + pc.getPort() );
            System.out.println( "websocket待完成作业启动,端口" + s.getPort() );
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        // TODO Auto-generated method stub

    }

}

7、PubCommentServer.java

package com.jeeplus.modules.websocket.pubComment;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import com.google.gson.Gson;
import com.jeeplus.common.config.DBContextHolder;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.res.entity.CollectivePreparation;
import com.jeeplus.modules.res.entity.CollectivePreparationTeacher;
import com.jeeplus.modules.res.service.CollectivePreparationService;
import com.jeeplus.modules.res.service.CollectivePreparationTeacherService;
import com.jeeplus.modules.sys.utils.UserPhotoUtils;
import com.jeeplus.modules.utils.entity.PubComment;
import com.jeeplus.modules.utils.service.PubCommentService;

public class PubCommentServer extends WebSocketServer {

    CollectivePreparationService collectivePreparationService = SpringContextHolder
            .getBean("collectivePreparationService");
    CollectivePreparationTeacherService collectivePreparationTeacherService = SpringContextHolder
            .getBean("collectivePreparationTeacherService");
    PubCommentService pubCommentService = SpringContextHolder.getBean("pubCommentService");

    public PubCommentServer(int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
    }

    public PubCommentServer(InetSocketAddress address) {
        super(address);
    }

    /**
     * 触发连接事件
     */
    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        // TODO Auto-generated method stub

    }

    /**
     * 触发关闭事件
     */
    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        // TODO Auto-generated method stub
        if (conn != null) {
            PubCommentServerPool.removeUser(conn);
        }
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        // TODO Auto-generated method stub
        if (message.startsWith("commentId:")) { // 学生宝app端消息
            PubCommentServerPool.addUser(message, conn);
        } else if (message.startsWith("zxytId:")) { // 内部成员评论
            String id = message.replace("zxytId:", "");
            // 发送消息至页面
            try {
                sendMessage(id);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else if (message.startsWith("SendComId:")) { // 评论
            String msgs = message.replace("SendComId:", "");

            String id = msgs.substring(msgs.indexOf(":") + 1, msgs.indexOf(","));
            String category = msgs.substring(msgs.lastIndexOf(",") + 1);
            // 发送消息至页面
            sendMessageByComment(id, category);

        }else if (message.startsWith("zoneArtileId:")) { // 空间评论
            String msgs = message.replace("zoneArtileId:", "");

            String id = msgs.substring(msgs.indexOf(":") + 1, msgs.indexOf(","));
            String category = msgs.substring(msgs.indexOf(",")+1, msgs.indexOf(",", msgs.indexOf(",")+1));
            String userId = msgs.substring(msgs.lastIndexOf(",") + 1);
            // 发送消息至页面
            sendMessageByZoneComment(id, category, userId);

        }
    }

    /**
     * 发送消息至空间评论页面
     * 
     * @param 
     * @throws ParseException
     */
    private void sendMessageByZoneComment(String id, String category, String userId) {
        DBContextHolder.setDbType("zone");
        PubComment pubComment = pubCommentService.get(id);
        DBContextHolder.clearContext();
        if (pubComment == null) {
            return;
        }

        if (pubComment.getPhoto()==null||StringUtils.isBlank(pubComment.getPhoto())||"/admin/logo/defaultPhoto/login.png".equals(pubComment.getPhoto())) {
            String path = UserPhotoUtils.getUPLOADURL().replace("/a/", "")+"/admin/logo/defaultPhoto/login.png";
            pubComment.setPhoto(path);
        }else{
            String path = UserPhotoUtils.getUPLOADURL()+"utils/pubEnclosure/showPhoto?tableName="+pubComment.getUserId();
            pubComment.setPhoto(path);
        }

        Gson gson = new Gson();
        String comment = gson.toJson(pubComment);
        String commentId = "commentId: " + pubComment.getTableRowId();
        List<WebSocket> webSockets = PubCommentServerPool.listByCommentLike(commentId);
        if(webSockets != null && webSockets.size() > 0){
            for (int i = 0; i < webSockets.size(); i++) {
                WebSocket conn = webSockets.get(i);
                conn.send("updatePubComment-" + comment);
            }
        } else {
            WebSocket conn = PubCommentServerPool.listByCommentLikeUser("loginId: "+userId);

            // 回复
            conn.send("updateReplyComment-"+ comment + "*" + "id-" + pubComment.getTableRowId());
        }

    }

    /**
     * 发送消息至公共评论页面
     * 
     * @param homeworkId
     * @throws ParseException
     */
    private void sendMessageByComment(String id, String category) {
        // 获取评论内容的主id,根据主id查评论表里的流程节点id
        List<PubComment> liComments = pubCommentService.findTableRowIdNonUser(id, category); // 根据节点id查找对象
        Gson gson = new Gson();
        String comments = "";
        if (liComments != null && liComments.size() > 0) {
            comments = gson.toJson(liComments);
        } else {
            comments += comments;
        }

        String commentId = "commentId:" + id;
        List<WebSocket> webSockets = PubCommentServerPool.listByCommentLike(commentId);
        for (int i = 0; i < webSockets.size(); i++) {
            WebSocket conn = webSockets.get(i);
            conn.send("updatePubComment-" + comments);
        }
    }

    /**
     * 发送消息至评论页面
     * 
     * @param homeworkId
     * @throws ParseException
     */
    private void sendMessage(String id) throws ParseException {
        DBContextHolder.setDbType("api");
        PubComment pubComment = pubCommentService.get(id);
        DBContextHolder.clearContext();
        if (pubComment == null) {
            return;
        }
        DBContextHolder.setDbType("res");
        // 根据备课id 获取参与获取主备课人ID
        CollectivePreparation preparation = collectivePreparationService.get(pubComment.getTableRowId());
        // 根据备课记录编码 查询参与备课的成员
        CollectivePreparationTeacher teacher = new CollectivePreparationTeacher();
        teacher.setPreparationId(preparation.getId());
        List<CollectivePreparationTeacher> teachers = collectivePreparationTeacherService.findAllList(teacher);
        DBContextHolder.clearContext();

        Set<String> ids = new HashSet<>();
        ids.add(preparation.getMainUserId());

        for (CollectivePreparationTeacher o : teachers) {
            ids.add(o.getUserId());
        }
        if (ids.contains(pubComment.getUserId())) {
            pubComment.setUserType(1);
        }
        if (pubComment.getPhoto()==null||StringUtils.isBlank(pubComment.getPhoto())||"/admin/logo/defaultPhoto/login.png".equals(pubComment.getPhoto())) {
            String path = UserPhotoUtils.getUPLOADURL().replace("/a/", "")+"/admin/logo/defaultPhoto/login.png";
            pubComment.setPhoto(path);
        }else{
            String path = UserPhotoUtils.getUPLOADURL()+"utils/pubEnclosure/showPhoto?tableName="+pubComment.getUserId();
            pubComment.setPhoto(path);
        }

        Gson gson = new Gson();
        String comment = gson.toJson(pubComment);
        String commentId = "commentId: " + preparation.getId();
        List<WebSocket> webSockets = PubCommentServerPool.listByCommentLike(commentId);
        for (int i = 0; i < webSockets.size(); i++) {
            WebSocket conn = webSockets.get(i);
            conn.send("updatePubComment-" + comment);
        }
    }

    /**
     * 触发异常事件(远程客户端异常关闭)
     */
    @Override
    public void onError(WebSocket conn, Exception ex) {
        // TODO Auto-generated method stub
        if (conn != null) {
            PubCommentServerPool.removeUser(conn);
        }
    }

}

8、PubCommentServerPool.java

package com.jeeplus.modules.websocket.pubComment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.java_websocket.WebSocket;

public class PubCommentServerPool {

    private static final Map<WebSocket,String> userconnections = new HashMap<WebSocket,String>();

    /**
     * 获取用户id
     * @param session
     */
    public static String getUserByKey(WebSocket conn){
        return userconnections.get(conn);
    }

    /**
     * 获取WebSocket
     * @param loginName
     */
    public static WebSocket getWebSocketByUser(String loginId){
        Set<WebSocket> keySet = userconnections.keySet();
        synchronized (keySet) {
            for (WebSocket conn : keySet) {
                String cuser = userconnections.get(conn);
                if(cuser.equals(loginId)){
                    return conn;
                }
            }
        }
        return null;
    }

    public static WebSocket listByCommentLikeUser(String loginId){

        Set<WebSocket> keySet = userconnections.keySet();
        synchronized (keySet) {
            for (WebSocket conn : keySet) {
                String start = userconnections.get(conn);
                if(start.endsWith(loginId)){
                    return conn;
                }
            }
        }
        return null;
    }

    /**
     * 获取WebSocket
     * @param loginName
     */
    public static List<WebSocket> listByCommentLike(String comment){

        List<WebSocket> webSockets = new ArrayList<WebSocket>();
        Set<WebSocket> keySet = userconnections.keySet();
        synchronized (keySet) {
            for (WebSocket conn : keySet) {
                String start = userconnections.get(conn);
                if(start.startsWith(comment)){
                    webSockets.add(conn);
                }
            }
        }
        return webSockets;
    }


    /**
     * 向连接池中添加连接
     * @param inbound
     */
    public static void addUser(String loginId, WebSocket conn){
        userconnections.put(conn,loginId);  //添加连接
    }


    /**
     * 移除连接池中的连接
     * @param inbound
     */
    public static boolean removeUser(WebSocket conn){
        if(userconnections.containsKey(conn)){
            userconnections.remove(conn);   //移除连接
            return true;
        }else{
            return false;
        }
    }

    /**
     * 向特定的用户发送数据
     * @param loginName
     * @param message
     */
    public static void sendMessageToUser(String loginId,String message){
        WebSocket conn = getWebSocketByUser(loginId);
        if(null != conn && null != userconnections.get(conn)){
            conn.send(message);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/moxiaoya1314/article/details/80274122