Tomcat8 websocket

参考:

http://niweiwei.iteye.com/blog/2019336

因为这篇文章是tomcat7的,那时候还没有Websocket 1.0规范,现在tomcat8已经删除了org.apache.catalina.websocket.WebSocketServlet,代码需要做相应的调整。

[codesyntax lang=”java5″]

package com.huqingyu;

import java.io.IOException;
import java.util.ArrayList;

import javax.websocket.*;    
import javax.websocket.server.ServerEndpoint;


@ServerEndpoint(value = "/ws")  
public class DemoServlet extends Endpoint {

    private static final long serialVersionUID = -4853540828121130946L;
    private static ArrayList<Session> mmiList = new ArrayList<Session>();

    //private static final Logger sysLogger = Logger.getLogger("sysLog");  
    @Override  
    public void onClose(Session session, CloseReason closeReason) {  
        System.out.println("onClose");
        mmiList.remove(session);
    }  
  
    @Override  
    public void onError(Session session, java.lang.Throwable throwable) {  
        System.out.println("onError");  
    }  
  
    @Override  
    public void onOpen(Session session, EndpointConfig config) {  
        System.out.println("onOpen");

        mmiList.add(session);
        session.addMessageHandler(new MyMessageHandle(session));  
 
    }  
  
    private class MyMessageHandle implements MessageHandler.Whole<String> {  
    	Session session =  null;  
        public MyMessageHandle(Session session){  
            this.session = session;        
            RemoteEndpoint.Basic remote =  session.getBasicRemote();  
    		try {
    			remote.sendText("Hello!");
    		} catch (IOException e) {
    		}
        }
  
        @Override  
        public void onMessage(String msg) {  
            try {  
                System.out.println("Accept Message : " + msg);
                for (Session s : mmiList) {
                    RemoteEndpoint.Basic remote =  s.getBasicRemote(); 
                	remote.sendText(msg);
                }
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  

}

[/codesyntax]