26 Haziran 2018 Salı

SpringWebSocket TextWebSocketHandler Sınıfı

Giriş
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<>();
  @Override
  public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    sessions.add(session);
    TextMessage message = new TextMessage("one-time message from server");
    session.sendMessage(message);
   }
  @Override
  public 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));
      }
    }
  }
  @Override
  public 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));
  }
  @Override
  public void handleTransportError(WebSocketSession session, Throwable exception) {...}
  @Override
  public 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