Пример #1
0
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
   if (!handshakeFuture.isDone()) {
     handshakeFuture.setFailure(cause);
   }
   for (WebSocketEventListener l : listensers) {
     l.onError(ctx, cause, response);
   }
   ctx.close();
 }
Пример #2
0
 protected boolean completeHandshake(ChannelHandlerContext ctx) {
   if (!handshaker.isHandshakeComplete()) {
     if (response != null && response.getStatus().code() > 299) {
       for (WebSocketEventListener l : listensers) {
         l.onError(ctx, null, response);
       }
       return true;
     }
     handshaker.finishHandshake(ctx.channel(), response);
     handshakeFuture.setSuccess();
     for (WebSocketEventListener l : listensers) {
       l.onConnect(ctx);
     }
     return true;
   }
   return false;
 }
Пример #3
0
  @Override
  public void channelRead0(final ChannelHandlerContext c, Object msg) throws Exception {
    Channel ch = ctx.channel();
    if (response == null) {
      if (msg instanceof FullHttpResponse) {
        response = (FullHttpResponse) msg;
      } else {
        response = new WSResponse((DefaultHttpResponse) msg, ctx.alloc().buffer());
      }
      if (completeHandshake(ctx)) {
        return;
      }
    }
    if (msg instanceof LastHttpContent) {
      return;
    }

    if (!(msg instanceof WebSocketFrame)) {
      throw new Exception(
          "Unexpected FullHttpResponse (getStatus="
              + response.getStatus()
              + ", "
              + "content="
              + response.content().toString(CharsetUtil.UTF_8)
              + ')');
    }

    final WebSocketFrame frame = (WebSocketFrame) msg;
    if (frame instanceof TextWebSocketFrame) {
      for (WebSocketEventListener l : listensers) {
        l.onMessage(c, new WebSocketMessage(((TextWebSocketFrame) frame).text()));
      }
    } else if (frame instanceof PingWebSocketFrame) {
      if (autoPong) {
        ctx.writeAndFlush(new PongWebSocketFrame(frame.content().copy()));
      }
      for (WebSocketEventListener l : listensers) {
        l.onPing(c, (PingWebSocketFrame) frame.copy());
      }
    } else if (frame instanceof PongWebSocketFrame) {
      Logger.getLogger(getClass())
          .warn(
              String.format(
                  "WebSocketClient received a PongWebSocketFrame, that shouldn't happen! Data : %s",
                  frame.content().toString(CharsetUtil.UTF_8)));
    } else if (frame instanceof CloseWebSocketFrame) {
      ch.close();
      for (WebSocketEventListener l : listensers) {
        l.onClose(c, (CloseWebSocketFrame) frame.copy());
      }
    }
  }
Пример #4
0
 @Override
 public void channelInactive(ChannelHandlerContext c) throws Exception {
   for (WebSocketEventListener l : listensers) {
     l.onClose(c, null);
   }
 }