这篇文章将简要演示如何利用Java Websocket API的编程式版本开发并部署(服务器与客户端)websocket端点。
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... }
该接口属于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(); } }
如果有必要,大家也可以创建自己的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"));
原文标题:Programmatic Websocket Endpoints in Java EE 7
【51CTO译稿,合作站点转载请注明原文译者和出处为51CTO.com】