當前位置:才華齋>IT認證>J2EE>

如何開發部署websocket端點

J2EE 閱讀(1.83W)

下面YJBYS小編為大家整理了關於如何利用Java Websocket API的程式設計式版本開發並部署(服務器與客戶端)websocket端點的文章,希望對你有所幫助。

如何開發部署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方法進行建立與設定。