下面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方法進行創建與設置。