2014年6月20日 星期五

JEE7 - WebSocket Client

Web Service 可使用的 WS Client, 每次使用前都先做 連線確認.
import java.io.IOException;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class WSClient {
    
    private static final Logger logger = Logger.getLogger("WSClient");

    private static WSClient instance = null;
    
    public static WebSocketContainer container = null;//
    public static Session session = null;
    
    public static String wsServerURL = "ws://localhost:8080/ws";
    
    // flag for connect of websocket
    public static boolean isConnect = false;
    
    public static WSClient createInstance(String wsServerURL) {
        logger.log(Level.INFO, "createInstance");
        WSClient.wsServerURL = wsServerURL;
        
        instance = new WSClient();
        instance.autoConnection(2);
        return instance;
    }
    
    public static void destroyInstance() {
        terminateToServer();
        instance = null;
    }
    
    public static WSClient getInstance() {
        return instance;
    }
    
    public boolean connectToServer() {
        try {
            // Tyrus is plugged via ServiceLoader API. See notes above
            container = ContainerProvider.getWebSocketContainer();

            // WS1 is the context-root of my web.app
            // ratesrv is the path given in the ServerEndPoint annotation on
            // server implementation
            session = container.connectToServer(WSClient.class, URI.create(wsServerURL));
            isConnect = true;
        } catch (Exception e) {
            e.printStackTrace();
            isConnect = false;
        }
        
        return isConnect;
    }
    
    public static void terminateToServer() {
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            session = null;
            container = null;
            isConnect = false;
        }
    }
    
    public synchronized void autoConnection(int retryCountLimit) {
        // 沒連線的情況下才進去
        if (!isConnect) {
            
            int retryCount = 0;
            do {
                retryCount++;
                connectToServer();
                
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {}
                
            } while (!isConnect && retryCount < retryCountLimit);
            
        }
    }
    
    public void send(String msg) {
        
        autoConnection(2);
        
        if (isConnect) {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    @OnOpen
    public void onOpen(Session session) {
        // same as above
        logger.log(Level.INFO, "onOpen" + session.getId());
        isConnect = true;
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        // the new USD rate arrives from the websocket server side.
        logger.log(Level.INFO, "onMessage: " + message);
    }
    
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        logger.log(Level.INFO, "onClose: " + session.getId());
        
        isConnect = false;
    }
    
}

沒有留言:

張貼留言