Websocket实现Java后台主动推送消息到前台

写在前面

需求: 项目测试, 缺少用户登录失败给admin推送消息, 想到这个方式, 当用户登录失败时, admin用户会在页面看到咣咣乱弹的alert. 

正文

pom.xml

        
        <dependency>
            <groupId>javax.websocketgroupId>
            <artifactId>javax.websocket-apiartifactId>
            <version>1.1version>
            <scope>providedscope>
        dependency>

        <dependency>
            <groupId>javaxgroupId>
            <artifactId>javaee-apiartifactId>
            <version>7.0version>
            <scope>providedscope>
        dependency>
        

Websocket.java

package com.jeecg.webSocket;

import net.sf.json.JSONObject;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/webSocket/{username}")
public class WebSocket {
    private static int onlineCount = 0;
    private static Map clients = new ConcurrentHashMap();
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) throws IOException {

        this.username = username;
        this.session = session;

        addOnlineCount();
        clients.put(username, this);
        System.out.println("已连接");
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(username);
        subOnlineCount();
    }

    @OnMessage
    public void onMessage(String message) throws IOException {

        JSONObject jsonTo = JSONObject.fromObject(message);
        String mes = (String) jsonTo.get("message");

        if (!jsonTo.get("To").equals("All")){
            sendMessageTo(mes, jsonTo.get("To").toString());
        }else{
            sendMessageAll("给所有人");
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    public void sendMessageTo(String message, String To) throws IOException {
        for (WebSocket item : clients.values()) {
            if (item.username.equals(To) )
                item.session.getAsyncRemote().sendText(message);
        }
    }

    public void sendMessageAll(String message) throws IOException {
        for (WebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

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

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

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

    public static synchronized Map getClients() {
        return clients;
    }
}

fineui_home.jsp

业务调用

WebSocket ws = new WebSocket();
JSONObject jo = new JSONObject();
jo.put("message", "这个比密码不对还想登录!");
jo.put("To", "admin");// 给用户名为admin的用户推送
try {
    ws.onMessage(jo.toString());
} catch (IOException e) {
    e.printStackTrace();
}

感谢

  • https://www.cnblogs.com/best/p/5695570.html

  • https://www.cnblogs.com/freud/p/8397934.html

 

转载于:https://www.cnblogs.com/yadongliang/p/11459903.html

你可能感兴趣的:(Websocket实现Java后台主动推送消息到前台)