Java webSocket 即时 消息推送

438 阅读2分钟

pop.xml 文件引用

         <!-- webSocket 消息推送 开始-->
	  	<dependency>
		    <groupId>javax.websocket</groupId>
		    <artifactId>javax.websocket-api</artifactId>
		    <version>1.1</version>
		    <scope>provided</scope>
		</dependency>
		 
		<dependency>
		    <groupId>javax</groupId>
		    <artifactId>javaee-api</artifactId>
		    <version>7.0</version>
		    <scope>provided</scope>
		</dependency>
	 	
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.28</version>
		</dependency> 
   
		<!-- webSocket 结束-->

前端使用 js :

    <script type="text/javascript">
			var eBody = Ext.getBody();
			var websocket = null;
			if ('WebSocket' in window) { 
			    websocket = new WebSocket('ws://'+location.host+'/kxdb/WebSocket/'+ orgid); 
			    websocket.onopen;
			} else { 
				Ext.MessageBox.alert('提示','当前浏览器不支持消息推送,请更新浏览器版本或更换浏览器!');
			} 
			
			//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 
			window.onbeforeunload = function() { 
			    closeWebSocket(); 
			} 
			   
			//关闭WebSocket连接 
			function closeWebSocket() { 
			    websocket.close(); 
			} 
			
			//创建window
			var mywin =  new Ext.Window({
				id:'mywin' ,		//如果你给组件加了一个id  那么这个组件就会被Ext所管理
				title: "财务报表上传",
			    width: 200,
			    height: 200,
			    layout: "fit",
			    closeAction:'hide',
			    x: eBody.getWidth() - 200,
		        y: eBody.getHeight() - 200,
		        items:[{
		        	 xtype: "textarea",
		        	 id:"CAmount",
		        	 anchor:"90%"
		        	 }]
			});	
		
	    	//接收到消息的回调方法 
			websocket.onmessage = function(event) {
			if(Ext.getCmp("CAmount").getValue() == undefined){
				Ext.getCmp("CAmount").setValue(event.data);
			}else{
				 Ext.getCmp("CAmount").setValue(event.data +"\n"+ Ext.getCmp("CAmount").getValue());
			}
			mywin.show();
			
		} 
    </script>

后台WebSocket.java 代码:

package com.myb.rcms.util;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSONObject;

@ServerEndpoint("/WebSocket/{orgid}")  
public class WebSocket { 
    private static int onlineCount = 0; 
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>(); 
    private Session session; 
    private String orgid; 
   
    @OnOpen 
    public void onOpen(@PathParam("orgid") String orgid, Session session) throws IOException { 
   
        this.orgid = orgid; 
        this.session = session; 
           
        addOnlineCount(); 
        clients.put(orgid, this);
        System.out.println("WebSocket已连接");
    } 
   
    @OnClose 
    public void onClose() throws IOException { 
        clients.remove(orgid); 
        System.out.println("已关闭WebSocket");
        subOnlineCount(); 
    } 
   
    @OnMessage 
    public void onMessage(String message) throws IOException { 
   
        JSONObject jsonTo = JSONObject.parseObject(message); //JSONObject.fromObject(message); 
        String mes = (String) jsonTo.get("message");
       
        if (!jsonTo.get("To").equals("All")){ 
        	
            sendMessageTo(mes, jsonTo.get("To").toString()); 
        }else{ 
            sendMessageAll(mes); 
        } 
    } 
   
    @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.orgid.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<String, WebSocket> getClients() { 
        return clients; 
    } 
}