JBoss搭建websockets

1. 创建 SocketConnectionCache 类

import com.cmb.dw.rtl.pbworkmng.service.sockets.QrC;

import java.util.concurrent.CopyOnWriteArraySet;

public class SocketConnectionCache {

    private static CopyOnWriteArraySet socketConnectionSet = new CopyOnWriteArraySet();

    private SocketConnectionCache() {
    }

    public static final SocketConnectionCache socketConnectionCache = new SocketConnectionCache();

    public static SocketConnectionCache getInstance() {
        return socketConnectionCache;
    }

    public void add(QrC qrc) {
        socketConnectionSet.add(qrc);
    }
    
    public void remove(QrC qrc) {
        socketConnectionSet.remove(qrc);
    }

    public CopyOnWriteArraySet getAll(){
        return socketConnectionSet;
    }
}

2.创建sockets类

import com.cmb.dw.rtl.pbworkmng.service.sockets.cache.SocketConnectionCache;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;

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

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

    private static final Logger       LOGGER = Logger.getLogger(QrC.class);
    private static int                      onlineCount  = 0;
    private String userID;
    private String positionID;

    private Session   session;

    //TCP链接建立成功自动调用该方法
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        SocketConnectionCache.getInstance().add(this);
        addOnlineCount();
        System.out.println("有一连接开启!当前在线人数为: " + QrC.onlineCount);
        LOGGER.info("有一连接开启!当前在线人数为: " + QrC.onlineCount);
    }

    //TCP连接断开自动调用该方法
    @OnClose
    public void onClose() {
        SocketConnectionCache.getInstance().remove(this);
        subOnlineCount();
        System.out.println("有一连接关闭!当前在线人数为: " + QrC.onlineCount);
        LOGGER.info("有一连接关闭!当前在线人数为: " + QrC.onlineCount);
    }

    public static synchronized void addOnlineCount() {
        //TODO: 改为增强一条数据库记录
        QrC.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        //TODO: 改为删除一条数据库记录
        QrC.onlineCount--;
    }

    //接收到来自客户端的消息的时候,自动调用
    @SuppressWarnings("unchecked")
    @OnMessage
    public void onMessage(String message, Session session) {
        LOGGER.info("pbworkmng:进入onMessage方法");
        ObjectMapper om = new ObjectMapper();
        Map map = null;
        try {
            map = om.readValue(message, Map.class);
        } catch (IOException e1) {
            LOGGER.error("数据读取错误!",e1);
        }
        LOGGER.info("map为:"+map.toString());
        this.userID = map.get("userID");
        this.positionID = map.get("positionID");
        LOGGER.info("接收到来自客户端的消息:userID为:"+userID+"******positionID为:"+positionID);
        /*if(map != null && ServiceConstants.LOGIN.equalsIgnoreCase(map.get("action"))){
            this.userID = map.get("userID");
            this.positionID = map.get("positionID");
            LOGGER.info("userID为:"+userID+"******positionID为:"+positionID);
            FrameworkModel model = new FrameworkModel();
            BaseBizService bizService = (BaseBizService)SpringContainer.getBean("MessageCountService");
            try {
                model.put(ServiceUtil.PARAMS_INFO, map);
                bizService.doValidate(model);
                model = bizService.doBusiness(model);
                LOGGER.info("消息数查询完毕!");
                singleSend(om.writeValueAsString(model.get("result")));
            } catch (FrameworkException e) {
                LOGGER.error("查询未读消息数出错!",e);
            } catch (JsonProcessingException e) {
                LOGGER.error("数据转换错误!",e);
            }
            
        }else if (map != null && "ping".equalsIgnoreCase(map.get("type"))) {
            Map resultPing = new HashMap();
            resultPing.put("type", "sping");
            try {
                singleSend(om.writeValueAsString(resultPing));
            } catch (JsonProcessingException e) {
                LOGGER.error("数据转换错误!", e);
            }
        }*/
    }
    
    public boolean isOpen(){
        return this.session.isOpen();
    }

    //收发消息出错都会调用这个方法
    @OnError
    public void onError(Session session, Throwable error) {
        //System.out.println("发生错误:"+error.toString());
        LOGGER.error(error.getMessage());
        LOGGER.error(error.toString());
    }

    public void sendMessage(String message) throws IOException {
        //同步发送消息(阻塞式)
        //this.session.getBasicRemote().sendText(message);
        //异步发送消息(非阻塞式)
        LOGGER.info("get QrC sendMessage method:" + message);
        this.session.getAsyncRemote().sendText(message);
    }

    public String getUserID() {
        return userID;
    }

    public String getPositionID() {
        return positionID;
    }

}

3.由服务器主动发消息至客户端

/**
     * 发送扫码接口至websockets
     * @param userID  登录用户号
     * @param positionID 登录用户岗位号
     * @param custScnQrCdSgnInf 扫码信息
     */
    private void sendMessage(String userID,String positionID, CustScnQrCdSgnInf custScnQrCdSgnInf) {
        ObjectMapper om = new ObjectMapper();
        Iterator it = SocketConnectionCache.getInstance().getAll().iterator();
        Map answer = null;
        while(it.hasNext()){
            QrC item = it.next();
            try {
                LOGGER.info("获取到消息(扫码结果):"+ custScnQrCdSgnInf.getSgnStsCd());
                LOGGER.info("在线数:"+SocketConnectionCache.getInstance().getAll().size());
                LOGGER.info("item.getUserID():"+item.getUserID()+"item.getPositionID():"+item.getPositionID()+"*****userID:"+userID+"positionID:"+positionID);
                LOGGER.info("item.isOpen():"+item.isOpen());
                if(item.isOpen() && item.getUserID() != null && item.getPositionID() != null) {
                    if(item.getUserID().equals(userID) && item.getPositionID().equals(positionID)) {
                        answer = new HashMap();
                        answer.put("data", custScnQrCdSgnInf.getSgnStsCd());
                        LOGGER.info("发送消息之前:"+om.writeValueAsString(answer));
                        item.sendMessage(om.writeValueAsString(answer));
                        LOGGER.info("Success to receive the message!!!"+item.getUserID()+"***"+item.getPositionID());
                    }
                }else{
                    LOGGER.info("连接已死,删除连接");
                    it.remove();
                }
            } catch (IOException e) {
                LOGGER.error("发送失败!原因:"+e.getMessage());
                continue;
            }
        }
    }

4.新增jboss-web.xml文件


	true

5.新增test2.html用于测试





Insert title here



	Welcome
	
UserID: PositionID:

6.pom.xml文件新增依赖


	javax
	javaee-api
	7.0
	provided

	commons-io
	commons-io
	2.5

7.JBoss版本为7.4.0以上

8.webapp目录下创建jboss文件夹-创建standalone.xml文件


  4.0.0
  LF39
  zhizhaonotify
  war
  0.0.1
  
		
			
				org.apache.maven.plugins
				maven-compiler-plugin
				3.1
				
					1.7
					1.7
					UTF-8
					true
				
			
		
  
  
	
		
			LF14
			rtlpubutil
			3.5.27
		
		
		
	        ZA21
	        edge-framework
	        2.0.10
	    
		
			LF14
			authcloudclient
			4.0.3
   			compile
		
		
			LF14
			escclient
			0.0.1
		
		
			commons-fileupload
			commons-fileupload
			1.3.1
		
		
			commons-io
			commons-io
			2.5
		
		
			javax
			javaee-api
			7.0
			provided
		
	
	
	
		
			default
			
				false
			
			
				true
			
		
	
		
			uat
			
				true
			
		
	
	
	
	
		
			ART-SEV01KF
			ART-SEV01KF-releases
			http://99.12.154.123/artifactory/third-cmb-release-local
		
		
			ART-SEV01KF
			ART-SEV01KF-snapshots
			http://99.12.154.123/artifactory/third-cmb-release-local
		
	

 

你可能感兴趣的:(java)