|
| 1 | +package com.secureskytech.demochatasync; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.net.URI; |
| 5 | +import java.time.Duration; |
| 6 | + |
| 7 | +import org.slf4j.Logger; |
| 8 | +import org.slf4j.LoggerFactory; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.stereotype.Component; |
| 11 | +import org.springframework.util.MultiValueMap; |
| 12 | +import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; |
| 13 | +import org.springframework.web.socket.CloseStatus; |
| 14 | +import org.springframework.web.socket.TextMessage; |
| 15 | +import org.springframework.web.socket.WebSocketSession; |
| 16 | +import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator; |
| 17 | +import org.springframework.web.socket.handler.TextWebSocketHandler; |
| 18 | +import org.springframework.web.socket.handler.WebSocketSessionDecorator; |
| 19 | +import org.springframework.web.util.UriComponentsBuilder; |
| 20 | + |
| 21 | +import com.secureskytech.demochatasync.service.SpringManagedActorSystem; |
| 22 | + |
| 23 | +import akka.actor.AbstractActorWithTimers; |
| 24 | +import akka.actor.ActorSystem; |
| 25 | +import akka.actor.Props; |
| 26 | +import akka.event.Logging; |
| 27 | +import akka.event.LoggingAdapter; |
| 28 | + |
| 29 | +@Component |
| 30 | +public class PlainWsDemoHandler extends TextWebSocketHandler { |
| 31 | + protected static final Logger LOG = LoggerFactory.getLogger(PlainWsDemoHandler.class); |
| 32 | + |
| 33 | + @Autowired |
| 34 | + SpringManagedActorSystem managedActorSystem; |
| 35 | + |
| 36 | + @Override |
| 37 | + public void afterConnectionEstablished(WebSocketSession session) throws Exception { |
| 38 | + LOG.info("websocket connection established."); |
| 39 | + LOG.info("WebSocketSession.getAcceptedProtocol()={}", session.getAcceptedProtocol()); |
| 40 | + session.getAttributes().forEach((k, v) -> { |
| 41 | + LOG.info("WebSocketSession.getAttributes()=[{},{}]", k, v); |
| 42 | + |
| 43 | + }); |
| 44 | + LOG.info("WebSocketSession.getBinaryMessageSizeLimit()={}", session.getBinaryMessageSizeLimit()); |
| 45 | + session.getHandshakeHeaders().forEach((headerName, headerValues) -> { |
| 46 | + headerValues.forEach(headerValue -> { |
| 47 | + LOG.info("WebSocketSession.getHandshakeHeaders()=[{}, {}]", headerName, headerValue); |
| 48 | + |
| 49 | + }); |
| 50 | + }); |
| 51 | + LOG.info("WebSocketSession.getId()={}", session.getId()); |
| 52 | + LOG.info("WebSocketSession.getLocalAddress()={}", session.getLocalAddress()); |
| 53 | + LOG.info("WebSocketSession.getPrincipal()={}", session.getPrincipal()); |
| 54 | + LOG.info("WebSocketSession.getRemoteAddress()={}", session.getRemoteAddress()); |
| 55 | + LOG.info("WebSocketSession.getTextMessageSizeLimit()={}", session.getTextMessageSizeLimit()); |
| 56 | + LOG.info("WebSocketSession.getUri()={}", session.getUri()); |
| 57 | + LOG.info("WebSocketSession.isOpen()={}", session.isOpen()); |
| 58 | + |
| 59 | + // これ、ここでwrapして正しいんだろうか・・・ |
| 60 | + final WebSocketSession concurrentSession = new ConcurrentWebSocketSessionDecorator(session, 1024 * 200, 200); |
| 61 | + |
| 62 | + final ActorSystem actorSystem = managedActorSystem.getActorSystem(); |
| 63 | + final URI uri = session.getUri(); |
| 64 | + MultiValueMap<String, String> parameters = UriComponentsBuilder.fromUri(uri).build().getQueryParams(); |
| 65 | + // 細かいエラーは無視する。 |
| 66 | + final long numOfCount = Long.parseLong(parameters.getFirst("numOfCount")); |
| 67 | + final long intervalSec = Long.parseLong(parameters.getFirst("intervalSec")); |
| 68 | + final int errval = Integer.parseInt(parameters.getFirst("errval")); |
| 69 | + actorSystem.actorOf( |
| 70 | + Props.create(AsyncCountUpTimerDemoActor.class, numOfCount, intervalSec, concurrentSession, errval)); |
| 71 | + } |
| 72 | + |
| 73 | + static class Tick0 { |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * N秒おきにカウントアップして {@link SseEmitter#send(Object)} し、指定カウントになったら終了する。 |
| 78 | + * コンストラクタオプションによっては途中で例外を発生させて、ビジネスロジック中での例外をエミュレートすることも可能。 |
| 79 | + */ |
| 80 | + static class AsyncCountUpTimerDemoActor extends AbstractActorWithTimers { |
| 81 | + final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); |
| 82 | + int count = 0; |
| 83 | + final long numOfCount; |
| 84 | + final WebSocketSessionDecorator session; |
| 85 | + final int errval; |
| 86 | + |
| 87 | + /** |
| 88 | + * @param numOfCount カウントアップ最大値 |
| 89 | + * @param intervalSec 何秒おきにカウントアップするかのスリープ秒数 |
| 90 | + * @param sseEmitter |
| 91 | + * @param errval カウントがこの値に到達したら div by zero を発生させる。 |
| 92 | + */ |
| 93 | + AsyncCountUpTimerDemoActor(final long numOfCount, final long intervalSec, |
| 94 | + final WebSocketSessionDecorator session, final int errval) { |
| 95 | + getTimers().startPeriodicTimer("tick0", new Tick0(), Duration.ofSeconds(intervalSec)); |
| 96 | + this.numOfCount = numOfCount; |
| 97 | + this.session = session; |
| 98 | + this.errval = errval; |
| 99 | + } |
| 100 | + |
| 101 | + @Override |
| 102 | + public void postStop() { |
| 103 | + if (session.isOpen()) { |
| 104 | + log.info("WebSocketSession is open, normal close."); |
| 105 | + try { |
| 106 | + session.close(CloseStatus.NORMAL); |
| 107 | + } catch (IOException e) { |
| 108 | + log.info("WebSocketSession close error: {}", e.getMessage()); |
| 109 | + } |
| 110 | + } |
| 111 | + log.info("async count-down timer stopped, called WebSocketSession.close(CloseStatus.NORMAL)."); |
| 112 | + } |
| 113 | + |
| 114 | + @Override |
| 115 | + public Receive createReceive() { |
| 116 | + return receiveBuilder().match(Tick0.class, tick -> { |
| 117 | + count++; |
| 118 | + log.info("tick {}/{}", count, numOfCount); |
| 119 | + try { |
| 120 | + // カウンタがerrvalに到達したら、div by zero を発生させる。 |
| 121 | + if (errval == count) { |
| 122 | + count = count / (errval - count); |
| 123 | + } |
| 124 | + } catch (ArithmeticException e) { |
| 125 | + log.info("div/zero => stop"); |
| 126 | + session.close(CloseStatus.SERVER_ERROR); |
| 127 | + getContext().stop(getSelf()); |
| 128 | + } |
| 129 | + if (count >= numOfCount) { |
| 130 | + log.info("tick count max => stop"); |
| 131 | + getContext().stop(getSelf()); |
| 132 | + } |
| 133 | + try { |
| 134 | + session.sendMessage(new TextMessage("count-" + count)); |
| 135 | + } catch (IOException e) { |
| 136 | + log.info("I/O error between peer connection : {} => stop", e.getMessage()); |
| 137 | + getContext().stop(getSelf()); |
| 138 | + } |
| 139 | + }).build(); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + @Override |
| 144 | + protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { |
| 145 | + LOG.info("websocket text message received."); |
| 146 | + LOG.info("WebSocketSession.getId()={}", session.getId()); |
| 147 | + LOG.info("WebSocketSession.getUri()={}", session.getUri()); |
| 148 | + LOG.info("WebSocketSession.isOpen()={}", session.isOpen()); |
| 149 | + // クライアントからテキストメッセージが送信されたら、"thx:" prefixを付けてecho-backする。 |
| 150 | + session.sendMessage(new TextMessage("thx:" + message.getPayload())); |
| 151 | + } |
| 152 | + |
| 153 | + @Override |
| 154 | + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { |
| 155 | + LOG.info("websocket connection established."); |
| 156 | + LOG.info("WebSocketSession.getId()={}", session.getId()); |
| 157 | + LOG.info("WebSocketSession.getUri()={}", session.getUri()); |
| 158 | + LOG.info("WebSocketSession.isOpen()={}", session.isOpen()); |
| 159 | + } |
| 160 | +} |
0 commit comments