下面YJBYS小编为大家整理了关于如何利用Java Websocket API的编程式版本开发并部署(服务器与客户端)websocket端点的文章,希望对你有所帮助。
第一步——扩展oint类
public class ProgrammaticEchoEnpoint extends Endpoint {
@Override
public void onOpen(Session session, EndpointConfig config) {
tln("Peer " + d() + " connected");
essageHandler(new e() {
@Override
public void onMessage(String message) {
try {
asicRemote()Text("Got message from " + d() + "n" + message);
} catch (IOException ex) {
}
}
});
}
@Override
public void onClose(Session session, CloseReason closeReason) {
tln("Peer " + d() + " disconnected due to " + easonPhrase());
}
@Override
public void onError(Session session, Throwable error) {
tln("Error communicating with peer " + d() + ". Detail: "+ essage());
}
}
接下来我们还要编写客户端端点(使用同样的API组合):
public class ProgrammaticEchoClient extends Endpoint {
@Override
public void onOpen(Session session, EndpointConfig config) {
tln("Connected to server");
}
//a message handler and other life cycle implementations have been skipped on purpose...
}
第二步——实现ServerApplicationConfig接口
该接口属于er包的组成部分,且能够通过覆写以实现端点部署中的定制化逻辑(适用于注释以及编程式端点)。
public class CustomServerAppConfigProvider implements ServerApplicationConfig {
@Override
public Set getEndpointConfigs(Set> endpointClasses) {
Set result = new HashSet<>();
for (Class epClass : endpointClasses) {
//need to ignore Client endpoint class
if (ls(s)) {
ServerEndpointConfig sec = te(epClass, "/letschat")d();
(sec);
}
}
return result;
}
@Override
public Set> getAnnotatedEndpointClasses(Set> scanned) {
return ySet();
}
}
怎样处理Client端点?
如果有必要,大家也可以创建自己的ClientEndpointConfig实例,并利用它对指向websocket服务器端点的连接进行初始化。
WebSocketContainer webSocketContainer = ebSocketContainer();
ClientEndpointConfig config = te()ders(s)d();
Session session = ectToServer(StockTickerClient()s, config,
new URI("ws://"));
注意事项:
客户端以及服务器端的ig对象只能为等同于(编程式)对象的@ServerEndpoint以及@ClientEndpoint注释元素(例如值、编码器、解码器以及配置器等等)。
各独立builder类(der与der)用于分别创建服务器与客户端配置实例。
ServerEndpointConfig实例的创建属于mandatory,因为服务器端点无法在不配合URI的前提下进行部署。不过这种情况在客户端端点方面不会出现——因为其全部作用就是接入现有服务器端点。
端点config(服务器&客户端)拥有configurator概念,其可通过对应builder方法进行创建与设置。