websocket通知

当用户一登录进来时,就在该页面建立相应的websocket(

如果你需要在某个页面操作相应功能,比如我在某个菜单下面的页面中,去给每个用户发送一个通知,那么就在这个页面中,发送通知完成后,调用

myNoticeSocket.send();这个方法

myNoticeSoket变量为

 new WebSocket("ws://" + document.location.host + ctx + "/admin/noticechat/#(userId)");)

,所以myNoticeSocket这个变量应该全局定义

前端:js

//以下代码为noticeWebsocket所用


initNoticeSocket();
//重置mySocket
function initNoticeSocket() {
    var myNoticeSocket = new WebSocket("ws://" + document.location.host + ctx + "/admin/noticechat/#(userId)");
    myNoticeSocket.onopen = function (message) {
        //setMessageInnerHTML("WebSocket连接成功");
    };
    myNoticeSocket.onclose = function (message) {
        //setMessageInnerHTML("WebSocket连接关闭");
    };
    myNoticeSocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    };
    window.onbeforeunload = function () {
        closeWebSocket();
    };
}

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


//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
    $.niftyNoty({
        type: 'dark',
        title: '欢迎!',
        message: innerHTML,
        container: 'floating',
        timer: 5000
    });

    $(".floating-container p").click(function () {
        doPjax(ctx + '/inbox');
    });
}

后端java:

package com.oa.controller.chat;


import com.oa.notice.dao.Inbox;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;


/**
 * Created by Yongfu Wei
 * 2017/9/20.
 * * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint(value = "/admin/noticechat/{friend}", configurator = GetHttpSessionConfigurator.class)
public class WebSocketTest {

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();


    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    private String to;

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(@PathParam("friend") String friend, Session session, EndpointConfig config) throws IOException {
        to = friend;
        this.session = session;
        webSocketSet.add(this); //加入set        addOnlineCount();           //在线数加1
        List<Inbox> list = Inbox.dao.getAllByUserId(friend);//查询当前用户下面的收件箱的信息
        this.session.getBasicRemote().sendText("您有" + list.size() + "条未处理的站内信,请及时查看处理!");
        System.out.println("noticeWebsocket有新连接加入!当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(@PathParam("friend") String friend, String message, Session session) {
        String[] split = message.split(",");
        // System.out.println("来自客户端的消息:" + message);
        //群发消息
        for (WebSocketTest item : webSocketSet) {
            try {
                for (int i = 0; i < split.length; i++) {
                    if (item.to.equals(split[i])) {
                        List<Inbox> list = Inbox.dao.getAllByUserId(item.to);//查询当前用户下面的收件箱的信息
                        item.sendMessage("您有" + list.size() + "条未处理的站内信,请及时查看处理!");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

    /**
     * 发生错误时调用
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    /**
     * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketTest.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketTest.onlineCount--;
    }
}


猜你喜欢

转载自blog.csdn.net/qq_34815027/article/details/78064053
今日推荐