tomcat websocket 长链接实现

1:首先在web.xml中配置Servlet  login.do对应MyWebSocketServletjava


MyWebSocketServlet代码以下:
web

package com.socket;


import javax.servlet.http.HttpServletRequest;


import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
public class MyWebSocketServlet extends WebSocketServlet {


public String getUser(HttpServletRequest request){
String userName = (String) request.getSession().getAttribute("yg_info_unique");
if(userName==null){
return null;
}
return userName;  
// return (String) request.getAttribute("user");  
}  

@Override
protected StreamInbound createWebSocketInbound(String arg0,
HttpServletRequest request) {
System.out.println(request.getSession().getId());
System.out.println("用户" +request.getSession().getAttribute("yg_info_unique") + "登陆");
String userName = (String) request.getSession().getAttribute("yg_info_unique");
String co_make = (String) request.getSession().getAttribute("co_make");
String is_part_hj = (String) request.getSession().getAttribute("is_part_hj");
String c_nick_name = (String) request.getSession().getAttribute("c_nick_name");
String init_state = (String) request.getSession().getAttribute("init_state");
String play_state = (String) request.getSession().getAttribute("play_state");
System.out.println(request.getSession().getAttribute("c_port"));
String port =  request.getSession().getAttribute("c_port")+"";
//System.out.println(InitServlet.getSocketList().size());
return new MyMessageInbound(userName,co_make,is_part_hj,c_nick_name,init_state,play_state,port); 
}
}
spring



2:在登录时保存登录人员惟一性sessionapache

3:在最外层界面使用ws:访问login.dojson

function startWebSocket() {
    if ('WebSocket' in window)
ws = new WebSocket("ws://"+s_ip+":"+s_port+"/qunhong_cdp_foa/login.do");
    else if ('MozWebSocket' in window)
        ws = new WebSocket("ws://"+s_ip+":"+s_port+"/qunhong_cdp_foa/login.do");
    else
        alert("not support");
服务器


4:在进入页面时与长链接握手以后进入websocket服务器中,服务器代码以下:websocket



package com.socket;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


import javax.servlet.http.HttpServletRequest;




import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
import org.apache.struts2.ServletActionContext;


import util.MessageUtil;




import com.alibaba.fastjson.JSONArray;
import com.opensymphony.xwork2.ActionContext;


public class MyMessageInbound extends MessageInbound {





private  String strSQL="";
private String name;
private String co_make;
private String is_part_hj;
private String c_nick_name;
private String init_state;
private String play_state;
private String port;
public static ConcurrentHashMap<String,HashMap> co_make_map=new ConcurrentHashMap<String,HashMap>();
HashMap yg_info_unique=new HashMap<String, HashMap>();
HashMap yg=new HashMap<String, HashMap>();
HashMap socket=new HashMap<String,HashMap>();
HashMap state=new HashMap<String, HashMap>();
public static int onLine_Sum=0;
public MyMessageInbound() {
super();
}


public MyMessageInbound(String name,String co_make,String is_part_hj,String c_nick_name,String init_state,String play_state,String port) {
super();
this.name = name;
this.co_make = co_make;
this.is_part_hj = is_part_hj;
this.c_nick_name = c_nick_name;
this.init_state = init_state;
this.play_state = play_state;
this.port = port;
}


@Override  
protected void onBinaryMessage(ByteBuffer arg0) throws IOException {  


}  





@Override  
protected void onTextMessage(CharBuffer msg) throws IOException { 
HashMap<String, HashMap> all_personnel=null;
HashMap<String,HashMap> json = null;
HashMap<String,String> type = null;
String send_type="";
String yg_info_unique="";
String co_makes="";
String bean_name="";
HashMap yg=null;
try {
yg=new HashMap();
type=MessageUtil.getType(msg);
bean_name=type.get("bean_name");
if(bean_name.equals("")){
json = MessageUtil.getMessage(msg,"0");//直接转换
}else{
json = MessageUtil.getMessage(msg,"1");//跳转类方法中处理
}
co_makes=type.get("co_make");
send_type=type.get("type");
yg_info_unique=type.get("yg_info_unique");

//上线用户集合类map
MessageInbound messageFromInbound =null;
WsOutbound outFromBound = null;
WsOutbound outbound = null;
CharBuffer fromMsg =  null;
if(!co_makes.equals("")){
all_personnel=new HashMap<String, HashMap>();
all_personnel=AllPersonnel(co_makes);
if(all_personnel.size()>0){
if(send_type.equals("0")){
for (String key : all_personnel.keySet()) {
yg=all_personnel.get(key);
messageFromInbound=(MessageInbound) yg.get("socket");
outFromBound = messageFromInbound.getWsOutbound();
fromMsg =  CharBuffer.wrap(JSONArray.toJSONString(json));
outFromBound.writeTextMessage(fromMsg);
outFromBound.flush();
}
}else{
yg=all_personnel.get(yg_info_unique);
messageFromInbound=(MessageInbound) yg.get("socket");
outFromBound = messageFromInbound.getWsOutbound();
fromMsg =  CharBuffer.wrap(JSONArray.toJSONString(json));
outFromBound.writeTextMessage(fromMsg);
outFromBound.flush();
}


}

}
} catch (Exception e) {
e.printStackTrace();
}finally{
all_personnel=null;
json = null;
type = null;
yg=null;
}  
}  


@Override  
protected void onClose(int status) {  
onLine_Sum-=1;
if(init_state.equals("1")){
HashMap<String,HashMap> json = null;
try{
if(co_make_map.get(co_make)!=null){
super.onClose(status);  
co_make_map.get(co_make).remove(name);
json= (HashMap<String, HashMap>) co_make_map.get(co_make).clone();
HashMap m=new HashMap();
m.put("method_name", "YgInfoMessage");
json.put("method", m);

}

HashMap yg=new HashMap();
//上线用户集合类map
MessageInbound messageFromInbound =null;
WsOutbound outFromBound = null;
WsOutbound outbound = null;
CharBuffer fromMsg =  null;
if(json.size()>0){
for (String key : json.keySet()) {
if(!key.equals("method")){
if(!key.equals("")){
yg=json.get(key);
messageFromInbound=(MessageInbound) yg.get("socket");
outFromBound = messageFromInbound.getWsOutbound();
fromMsg =  CharBuffer.wrap(JSONArray.toJSONString(json));
outFromBound.writeTextMessage(fromMsg);
outFromBound.flush();
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}

            new Thread(new Runnable() {  
                public void run() {  
                 ConcurrentHashMap<String,HashMap> map=null;
                 try {
                 int sum=0;
                 map=new ConcurrentHashMap<String, HashMap>();
                 map=co_make_map;
                 for (Object key:map.keySet()) {
HashMap personnel=(HashMap)map.get(key);
sum+=personnel.size();
}
                 write(sum+"");
} catch (Exception e) {
// TODO: handle exception
}
                
                }  
            }).start();  
}  


@Override
protected void onOpen(WsOutbound outbound) {
onLine_Sum+=1;
boolean flag=false;
super.onOpen(outbound);  
//登陆的用户注册进去

if(init_state!=null&&init_state.equals("1")){
if(name!=null){
if(co_make_map.get(co_make)==null){
flag=true;
}
if(flag){
 yg=new HashMap<String, HashMap>();
 socket=new HashMap<String, HashMap>();
 state=new HashMap<String, HashMap>();
 yg_info_unique=new HashMap<String, HashMap>();
     state.put("online_state", 1);
     state.put("is_part_hj", is_part_hj);
     state.put("th_state", "0");
     state.put("contract_name", "");
     yg_info_unique.put("state", state);
 yg_info_unique.put("socket", this);
 yg_info_unique.put("yg_name", c_nick_name);
 yg.put(name, yg_info_unique);
     co_make_map.put(co_make, yg);
}else{
 state.put("online_state", 1);
 state.put("is_part_hj", is_part_hj);
 state.put("th_state", "0");
 state.put("contract_name", "");
     yg_info_unique.put("state", state);
 yg_info_unique.put("socket", this);
 yg_info_unique.put("yg_name", c_nick_name);
 co_make_map.get(co_make).put(name, yg_info_unique);
}


 
}




}
new Thread(new Runnable() {  

            public void run() {  
             ConcurrentHashMap<String,HashMap> map=null;
             try {
             int sum=0;
             map=new ConcurrentHashMap<String, HashMap>();
             map= co_make_map;
                 for (Object key:map.keySet()) {
     HashMap personnel=(HashMap)map.get(key);
     sum+=personnel.size();
     }
                 write(sum+"");
} catch (Exception e) {
e.printStackTrace();
}finally{
map=null;
}
            
            }  
        }).start();  
}







@Override
public int getReadTimeout() {
return 0;
}  





public HashMap AllPersonnel(String co_make){
HashMap  maps=new HashMap();
try {

if(co_make_map.size()>0){
maps= (HashMap) co_make_map.get(co_make).clone();
}
   
} catch (Exception e) {
e.printStackTrace();
}


return maps;

}


 
 
 /**
     * 写入文件
     * 
     * @param writePath
     *            文件路径
     */
    public  void write(String writeTxt) {
     String webroot = System.getProperty("qunhong_cdp_foa");
        try {
            File f = new File(webroot+"websocket/"+port+".txt");
            if (!f.exists()) {
                f.createNewFile();
            }
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(writeTxt);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
session



5:MessageUtil代码以下:socket



package util;


import java.lang.reflect.Method;
import java.nio.CharBuffer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


import javax.servlet.jsp.JspWriter;


import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.socket.MyMessageInbound;
import com.qh_goal.DictList;
public class MessageUtil {
public static HashMap getMessage(CharBuffer msg,String type) throws JSONException {
HashMap<String,String> map = new HashMap<String,String>();
String msgString  = msg.toString();
map=(HashMap<String, String>) toMap(msgString);
if(type.equals("0")){
return map;
}else{
HashMap rel=getJson(map);
return rel;
}
}

public static HashMap getMessageInterface(String msg) throws JSONException {
HashMap<String,String> map = new HashMap<String,String>();
String msgString  = msg.toString();
map=(HashMap<String, String>) toMap(msgString);
for (int i = 0; i < map.size(); i++) {

}
return map;
}

public static HashMap getType(CharBuffer msg){
HashMap<String,String> map = new HashMap<String,String>();
HashMap<String,String> map_result = new HashMap<String,String>();
String msgString  = msg.toString();
String type="";
String yg_info_unique="";
String co_make="";
String bean_name="";
ConcurrentHashMap<String,HashMap> maps=null;
try {
map=(HashMap<String, String>) toMap(msgString);
maps=MyMessageInbound.co_make_map;
if(map.size()>0){
type=map.get("type").toString();
yg_info_unique=map.get("yg_info_unique").toString();
bean_name=map.get("bean_name").toString();
if(MyMessageInbound.co_make_map.size()>0){
for (Object key : maps.keySet()) {
if(maps.get(key).get(yg_info_unique)!=null){

co_make=key.toString();

break;
}
}
}

map_result.put("co_make", co_make);
map_result.put("bean_name", bean_name);
map_result.put("type", type);
map_result.put("yg_info_unique", yg_info_unique);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
map=null;
maps=null;
}
return map_result;

}


public static HashMap getJson(HashMap map){
String parameter="";
String bean_name="";
String method_name="";
String type="";
String yg_info_unique="";
JspWriter out = null ;
Class clazz=null;
Object str=null;
try {
if(map.size()>0){
parameter=map.get("parameter").toString();
bean_name=map.get("bean_name").toString();
method_name=map.get("method_name").toString();
type=map.get("type").toString();
yg_info_unique=map.get("yg_info_unique").toString();
}

if(DictList.AllClass.get(bean_name)!=null){
  clazz=(Class)newInstance(DictList.AllClass.get(bean_name));
}

Object []sb=(method_name+","+parameter).split(",");
str=getMethod(method_name, clazz.newInstance(), sb);

} catch (Exception e){;
e.printStackTrace();
}
return (HashMap)str;
}



 /**
     * 
     * @param className
     * @return 
     */
    @SuppressWarnings("unchecked")
public static Class getclass(String className){
        Class c=null;
        try {
            c=Class.forName(className);
        } catch (ClassNotFoundException ex) {
        }
        return c;
    }
    
    /**
     * 
     * @param MethodName 
     * @param o          
     * @param paras     
     */
    @SuppressWarnings("unchecked")
public static Object  getMethod(String MethodName,Object o,Object []paras,Object obj){
         Class c[]=null;
         String result="";
         Object[] so=new Object[paras.length+1];
         for (int i = 0; i < paras.length; i++) {
          so[i]=paras[i];
}
         so[paras.length]=obj;
         if(paras!=null){
             int len=paras.length+1;
             c=new Class[len];
             for(int i=0;i<len-1;++i){
                 c[i]=paras[i].getClass();
             }
             c[paras.length]=obj.getClass();
         }
        try {
            Method method=o.getClass().getDeclaredMethod(MethodName,c);
            try {
                 result=(String) method.invoke(o,so);
            } catch (Exception ex) {
             ex.printStackTrace();
            }
        }catch (Exception e) {
         e.printStackTrace();
}
return result;
    }
    
    
    @SuppressWarnings("unchecked")
public static Object  getMethod(String MethodName,Object o,Object []paras){
         Class c[]=null;
         Object result="";
       
        try {
           if(paras!=null){
                  int len=paras.length;
                  c=new Class[len];
                  for(int i=0;i<len;++i){
                      c[i]=paras[i].getClass();
                  }
              }
            Method method=o.getClass().getDeclaredMethod(MethodName,c);
            result= method.invoke(o,paras);
        }catch (Exception e) {
         e.printStackTrace();
}
return result;
    }
    
    /**
     * 将Json对象转换成Map
     * 
     * @param jsonObject
     *            json对象
     * @return Map对象
     * @throws JSONException
     */
    public static Map toMap(String jsonString) throws JSONException {


        JSONObject jsonObject = new JSONObject(jsonString);
        
        Map result = new HashMap();
        Iterator iterator = jsonObject.keys();
        String key = null;
        String value = null;
        
        while (iterator.hasNext()) {


            key = (String) iterator.next();
            value = jsonObject.getString(key);
            result.put(key, value);


        }
        return result;


    }
    public static Object newInstance(String className)throws Exception{
        Class clazz=Class.forName(className);
        return clazz;
}
}
jsp