Giriş
AbstractWebSocketHandler sınıfından kalıtır
AbstractWebSocketHandler sınıfından kalıtır
İskeleti şöyledir. WebSocketHandler sınıfının broadcast yeteneği olmadığı için burada taklit ediliyor.
public class ServerWebSocketHandler extends TextWebSocketHandler
implements SubProtocolCapable {private final Set<WebSocketSession> sessions = new CopyOnWriteArraySet<>();@Overridepublic void afterConnectionEstablished(WebSocketSession session) throws Exception {sessions.add(session);TextMessage message = new TextMessage("one-time message from server");session.sendMessage(message);}@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) {sessions.remove(session);}@Scheduled(fixedRate = 10000)void sendPeriodicMessages() throws IOException {for (WebSocketSession session : sessions) {if (session.isOpen()) {String broadcast = "server periodic message " + LocalTime.now();session.sendMessage(new TextMessage(broadcast));}}}@Overridepublic void handleTextMessage(WebSocketSession session, TextMessage message)
throws Exception {String request = message.getPayload();String response = String.format("response from server to '%s'",
HtmlUtils.htmlEscape(request));session.sendMessage(new TextMessage(response));}@Overridepublic void handleTransportError(WebSocketSession session, Throwable exception) {...}@Overridepublic List<String> getSubProtocols() {return Collections.singletonList("subprotocol.demo.websocket");}}
handleTextMessage metodu
İmzası şöyle.@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws IOException, InterruptedException;
Örnek
Şöyle yaparız
@Component
public class WebSocketHandler extends AbstractWebSocketHandler {
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message)
throws IOException {
String payload = message.getPayload();
session.sendMessage(new TextMessage("..."));
}
}
Hiç yorum yok:
Yorum Gönder