WebSocket 初次使用,jfinal框架下

java代码

package org.framework.jfinal.socket.processor;

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

@ServerEndpoint("/WebSocket2")
public class WebSocket2 {

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
    private static CopyOnWriteArraySet<WebSocket2> webSocketSet = new CopyOnWriteArraySet<WebSocket2>();

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

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

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

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

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

    /**
     * 连接建立成功调用的方法
     *
     * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session) throws IOException, ExecutionException, InterruptedException {
        System.out.println("websocket已连接");
        this.webSocketSession = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        //打开socket客户端
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
    }

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

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        //群发消息
        for (WebSocket2 item : webSocketSet) {
            try {
                if (message.startsWith("AA")) {
                    item.sendMessage(message + "连接正常");
                } else {
                    item.sendMessage(message);
                }

            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }


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

}

    @Override
    public void configHandler(Handlers me) {
        me.add(new ContextPathHandler("ctx"));
        me.add(new WebSocketHandler("/WebSocket2"));
    }

js

//初始化webSocket
var wsOPC = null;
function initOPCWebSocket2() {
    wsOPC = new WebSocket('ws://127.0.0.1:8080/swj/WebSocket2');
    wsOPC.onopen = function () {
        console.log("客户端已连接");
    }
    wsOPC.onmessage = function (evt) {
        console.log("客户端接收消息 ", evt.data);
        console.log("indexOf ", evt.data.indexOf('AA'));

        if (evt.data.indexOf('AA') > -1) {
            $(".tianMaCoon img").attr('src', '/swj/views/detail/script/images/alarm/greenLight.png?t=' + new Date());
        }
        else {
            $(".tianMaCoon img").attr('src', '/swj/views/detail/script/images/alarm/redLight.png?t=' + new Date());
        }
    }
    wsOPC.onclose = function () {
        console.log("客户端已断开连接");
    };
    wsOPC.onerror = function (evt) {
        console.log("连接出现错误", evt.data);
    };
    setTimeout(function () {
        wsOPC.send("BB");
    }, 2000);
    setTimeout(function () {
        wsOPC.send("AA");
    }, 3000);

}
posted @ 2020-09-08 11:42  一只桔子2233  阅读(661)  评论(0编辑  收藏  举报