Java EE 7當中的編程式Websocket端點

jopen 9年前發布 | 18K 次閱讀 WebSocket Java EE Java開發

這篇文章將簡要演示如何利用Java Websocket API的編程式版本開發并部署(服務器與客戶端)websocket端點。

第一步——擴展javax.websocket.Endpoint類

public class ProgrammaticEchoEnpoint extends Endpoint { 
 
    @Override 
 
    public void onOpen(Session session, EndpointConfig config) { 
 
        System.out.println("Peer " + session.getId() + " connected"); 
 
        session.addMessageHandler(new MessageHandler.Whole<String>() { 
 
            @Override 
 
            public void onMessage(String message) { 
 
                try { 
 
                    session.getBasicRemote().sendText("Got message from " + session.getId() + "\n" + message); 
 
                } catch (IOException ex) { 
 
                } 
 
            } 
 
        }); 
 
    } 
 
    @Override 
 
    public void onClose(Session session, CloseReason closeReason) { 
 
        System.out.println("Peer " + session.getId() + " disconnected due to " + closeReason.getReasonPhrase()); 
 
    } 
 
    @Override 
 
    public void onError(Session session, Throwable error) { 
 
        System.out.println("Error communicating with peer " + session.getId() + ". Detail: "+ error.getMessage()); 
 
    } 
 
} 

接下來我們還要編寫客戶端端點(使用同樣的API組合):

public class ProgrammaticEchoClient extends Endpoint { 
 
    @Override 
 
    public void onOpen(Session session, EndpointConfig config) { 
 
        System.out.println("Connected to server"); 
 
    } 
 
    //a message handler and other life cycle implementations have been skipped on purpose... 
 
} 

第二步——實現ServerApplicationConfig接口

該接口屬于javax.websocket.server包的組成部分,且能夠通過覆寫以實現端點部署中的定制化邏輯(適用于注釋以及編程式端點)。

public class CustomServerAppConfigProvider implements ServerApplicationConfig { 
 
    @Override 
 
    public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) { 
 
        Set<ServerEndpointConfig> result = new HashSet<>(); 
 
        for (Class epClass : endpointClasses) { 
 
            //need to ignore Client endpoint class 
 
            if (epClass.equals(ProgrammaticChatEndpoint.class)) { 
 
                ServerEndpointConfig sec = ServerEndpointConfig.Builder.create(epClass, "/letschat").build(); 
 
                result.add(sec); 
 
            } 
 
        } 
 
        return result; 
 
    } 
 
    @Override 
 
    public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) { 
 
        return Collections.emptySet(); 
 
    } 
 
} 

怎樣處理Client端點?

如果有必要,大家也可以創建自己的ClientEndpointConfig實例,并利用它對指向websocket服務器端點的連接進行初始化。

WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer(); 
 
ClientEndpointConfig config = ClientEndpointConfig.Builder.create().decoders(StockTickDecoder.class).build(); 
 
Session session = webSocketContainer.connectToServer(StockTickerClient().class, config,  
 
                                                    new URI("ws://hotstocks.com/ticker")); 

注意事項:

  • 客戶端以及服務器端的config對象只能為等同于(編程式)對象的@ServerEndpoint以及@ClientEndpoint注釋元素(例如值、編碼器、解碼器以及配置器等等)。
  • 各獨立builder類(ServerEndpointConfig.Builder與ClientEndpointConfig.Builder)用于分別創建服務器與客戶端配置實例。
  • ServerEndpointConfig實例的創建屬于mandatory,因為服務器端點無法在不配合URI的前提下進行部署。不過這種情況在客戶端端點方面不會出現——因為其全部作用就是接入現有服務器端點。
  • 端點config(服務器&客戶端)擁有configurator概念,其可通過對應builder方法進行創建與設置。
  • 接下來我們還將發布更多與Websocket相關的指導性文章,各位敬請期待。

原文標題:Programmatic Websocket Endpoints in Java EE 7

【51CTO譯稿,合作站點轉載請注明原文譯者和出處為51CTO.com】

來自: http://developer.51cto.com/art/201601/504283.htm

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!