MyWebSocket.java 4.34 KB
package com.glsx.usercenter.component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.common.constants.ResultObject;
import com.glsx.usercenter.constants.ResultCodeEnum;

/**
 * 
 * @Title MyWebSocket.java
 * @Package com.glsx.usercenter.component
 * @Description TODO websocket的配置
 * @author zhanghj
 * @date 2019年8月16日 下午2:32:55
 * @version 1.0.0
 */
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class MyWebSocket {

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

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    public static ConcurrentHashMap<Integer, MyWebSocket> webSocketSet = new ConcurrentHashMap<Integer, MyWebSocket>(16);
    
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    private static Logger log = LoggerFactory.getLogger(MyWebSocket.class);


    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(@PathParam(value="userId") Integer userId,Session session) {
    	log.info("userId="+userId);
        this.session = session;
        addWebSocketSet(userId, this);
    }

    private void addWebSocketSet(Integer userId, MyWebSocket myWebSocket) {
		// TODO Auto-generated method stub
		if (webSocketSet.containsKey(userId)) {
			webSocketSet.replace(userId, myWebSocket);
		} else {
			webSocketSet.put(userId, myWebSocket);
			addOnlineCount();           //在线数加1
	        log.info("有新连接加入!当前在线人数为" + getOnlineCount());
		}
	}

	/**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam(value="userId") Integer userId) {
        webSocketSet.remove(userId);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) throws Exception {
        this.session = session;
        message = "来自客户端的消息:" + message;
        log.info(message);
        try {
        	JSONObject json = new JSONObject();
        	sendMessage( json);
        } catch (Exception e) {
            log.error("onMessage方法异常"+e.toString());
            e.printStackTrace();
        }
        //群发消息
//        sendInfo("群发消息"+message);
    }

    /**
     * 发生错误时调用
     @OnError
     **/
     public void onError(Session session, Throwable error) {
         log.error("onMessage方法异常"+error.toString());
         error.printStackTrace();
     }


    /**
     * 发送消息需注意方法加锁synchronized,避免阻塞报错
     * 注意session.getBasicRemote()与session.getAsyncRemote()的区别
     * @param message
     * @throws IOException
     * @throws EncodeException 
     */
     public synchronized void sendMessage(JSONObject message) throws IOException, EncodeException {
         //this.session.getBasicRemote().sendText(message);
    	 ResultObject result = new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), message);
    	 this.session.getAsyncRemote().sendText(JSON.toJSONString(result));
     }

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

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

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