コード例 #1
0
  @Override
  public void parseCommand(String[] message, ChannelHandlerContext ctx) {
    String password = message[0];

    if (password.equals("cometServer")) {
      String command = message[1];

      switch (command) {
        default:
          {
            ctx.channel().writeAndFlush("response||You're connected!");
            break;
          }

        case "stats":
          {
            ctx.channel()
                .writeAndFlush("response||" + JsonFactory.getInstance().toJson(CometStats.get()));
            break;
          }
      }
    } else {
      ctx.disconnect();
    }
  }
コード例 #2
0
 @Override
 public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
   LOG.error(cause.getMessage(), cause);
   if (context.channel().isOpen()) {
     context.channel().close();
   }
 }
コード例 #3
0
 @Override
 protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
   RequestWrapper request = (RequestWrapper) msg;
   long beginTime = System.currentTimeMillis();
   ResponseWrapper responseWrapper =
       ProtocolFactory.getServerHandler(request.getProtocolType()).handleRequest(request);
   final int id = request.getId();
   // already timeout,so not return
   if ((System.currentTimeMillis() - beginTime) >= request.getTimeout()) {
     LOGGER.warn(
         "timeout,so give up send response to client,requestId is:"
             + id
             + ",client is:"
             + ctx.channel().remoteAddress()
             + ",consumetime is:"
             + (System.currentTimeMillis() - beginTime)
             + ",timeout is:"
             + request.getTimeout());
     return;
   }
   ChannelFuture wf = ctx.channel().writeAndFlush(responseWrapper);
   wf.addListener(
       new ChannelFutureListener() {
         public void operationComplete(ChannelFuture future) throws Exception {
           if (!future.isSuccess()) {
             LOGGER.error("server write response error,request id is: " + id);
           }
         }
       });
 }
コード例 #4
0
ファイル: NetworkDispatcher.java プロジェクト: trixmot/mod1
 // if we add any attributes, we should force removal of them here so that
 // they do not hold references to the world and causes it to leak.
 private void cleanAttributes(ChannelHandlerContext ctx) {
   ctx.channel().attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).remove();
   ctx.channel().attr(NetworkRegistry.NET_HANDLER).remove();
   ctx.channel().attr(NetworkDispatcher.FML_DISPATCHER).remove();
   this.handshakeChannel.attr(FML_DISPATCHER).remove();
   this.manager.channel().attr(FML_DISPATCHER).remove();
 }
コード例 #5
0
  /**
   * Called on exceptions in the client handler pipeline.
   *
   * <p>Remote exceptions are received as regular payload.
   */
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    if (cause instanceof TransportException) {
      notifyAllChannelsOfErrorAndClose(cause);
    } else {
      final SocketAddress remoteAddr = ctx.channel().remoteAddress();

      final TransportException tex;

      // Improve on the connection reset by peer error message
      if (cause instanceof IOException && cause.getMessage().equals("Connection reset by peer")) {

        tex =
            new RemoteTransportException(
                "Lost connection to task manager '"
                    + remoteAddr
                    + "'. This indicates "
                    + "that the remote task manager was lost.",
                remoteAddr,
                cause);
      } else {
        tex = new LocalTransportException(cause.getMessage(), ctx.channel().localAddress(), cause);
      }

      notifyAllChannelsOfErrorAndClose(tex);
    }
  }
コード例 #6
0
  private void handleHTTP(OutPacketMessage msg, ChannelHandlerContext ctx, ChannelPromise promise)
      throws IOException {
    Channel channel = ctx.channel();
    Attribute<Boolean> attr = channel.attr(WRITE_ONCE);

    Queue<Packet> queue = msg.getClientHead().getPacketsQueue(msg.getTransport());

    if (!channel.isActive() || queue.isEmpty() || !attr.compareAndSet(null, true)) {
      promise.setSuccess();
      return;
    }

    ByteBuf out = encoder.allocateBuffer(ctx.alloc());
    Boolean b64 = ctx.channel().attr(EncoderHandler.B64).get();
    if (b64 != null && b64) {
      Integer jsonpIndex = ctx.channel().attr(EncoderHandler.JSONP_INDEX).get();
      encoder.encodeJsonP(jsonpIndex, queue, out, ctx.alloc(), 50);
      String type = "application/javascript";
      if (jsonpIndex == null) {
        type = "text/plain";
      }
      sendMessage(msg, channel, out, type, promise);
    } else {
      encoder.encodePackets(queue, out, ctx.alloc(), 50);
      sendMessage(msg, channel, out, "application/octet-stream", promise);
    }
  }
コード例 #7
0
  private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
    if (logger.isLoggable(Level.FINE)) {
      logger.fine(
          String.format(
              "Channel %s received %s",
              ctx.channel().hashCode(), frame.getClass().getSimpleName()));
    }

    if (frame instanceof CloseWebSocketFrame) {
      handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
    } else if (frame instanceof PingWebSocketFrame) {
      ctx.write(new PongWebSocketFrame(frame.isFinalFragment(), frame.rsv(), frame.content()));
    } else if (frame instanceof TextWebSocketFrame) {
      ctx.write(frame);
    } else if (frame instanceof BinaryWebSocketFrame) {
      ctx.write(frame);
    } else if (frame instanceof ContinuationWebSocketFrame) {
      ctx.write(frame);
    } else if (frame instanceof PongWebSocketFrame) {
      frame.release();
      // Ignore
    } else {
      throw new UnsupportedOperationException(
          String.format("%s frame types not supported", frame.getClass().getName()));
    }
  }
コード例 #8
0
 /**
  * 取代netty3.0中的channelDisconnected(),客户端主动关闭连接
  *
  * @param ctx
  * @throws Exception
  */
 @Override
 public void channelInactive(ChannelHandlerContext ctx) throws Exception {
   logger.info("[" + ctx.channel().remoteAddress() + "] : is inactive......");
   handlerDispatcher.removeChannelInfo(ctx.channel());
   System.out.println("[" + ctx.channel().remoteAddress() + "] : is inactive......");
   ctx.close();
 }
コード例 #9
0
  private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {
    // Handle a bad request.
    if (!req.getDecoderResult().isSuccess()) {
      sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
      req.release();
      return;
    }

    // Allow only GET methods.
    if (req.getMethod() != GET) {
      sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
      req.release();
      return;
    }

    // Handshake
    WebSocketServerHandshakerFactory wsFactory =
        new WebSocketServerHandshakerFactory(
            getWebSocketLocation(req), null, false, Integer.MAX_VALUE);
    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
      WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
      handshaker.handshake(ctx.channel(), req);
    }
    req.release();
  }
コード例 #10
0
  /**
   * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward to the next {@link
   * ChannelHandler} in the {@link ChannelPipeline}.
   *
   * <p>Sub-classes may override this method to change behavior.
   */
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    NettyMessage message = (NettyMessage) msg;

    // 如果是握手请求消息,处理,其它消息透传
    if (message.getHeader() != null
        && message.getHeader().getType() == MessageType.LOGIN_REQ.value()) {
      String nodeIndex = ctx.channel().remoteAddress().toString();
      NettyMessage loginResp = null;
      // 重复登陆,拒绝
      if (nodeCheck.containsKey(nodeIndex)) {
        loginResp = buildResponse((byte) -1);
      } else {
        InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
        String ip = address.getAddress().getHostAddress();
        boolean isOK = false;
        for (String WIP : whitekList) {
          if (WIP.equals(ip)) {
            isOK = true;
            break;
          }
        }
        loginResp = isOK ? buildResponse((byte) 0) : buildResponse((byte) -1);
        if (isOK) nodeCheck.put(nodeIndex, true);
      }
      System.out.println(
          "The login response is : " + loginResp + " body [" + loginResp.getBody() + "]");
      ctx.writeAndFlush(loginResp);
    } else {
      ctx.fireChannelRead(msg);
    }
  }
コード例 #11
0
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
   logger.error("[" + ctx.channel().remoteAddress() + "] 出异常……");
   //		cause.printStackTrace();
   handlerDispatcher.removeChannelInfo(ctx.channel());
   ctx.close();
 }
コード例 #12
0
  private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

    System.out.println("pre1:" + frame);

    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
      handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
      return;
    }
    if (frame instanceof PingWebSocketFrame) {
      ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
      return;
    }
    if (!(frame instanceof TextWebSocketFrame)) {
      throw new UnsupportedOperationException(
          String.format("%s frame types not supported", frame.getClass().getName()));
    }

    WebsocketMessageHandlerI websocketMessageHandler = new WebSocketMessageHander(ctx, channels);
    // Send the uppercase string back.

    String requestRaw = ((TextWebSocketFrame) frame).text();

    websocketMessageHandler.handleMessage(requestRaw);
  }
コード例 #13
0
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

    FullHttpRequest req = (FullHttpRequest) msg;
    String upgrade = req.headers().get(HttpHeaders.Names.UPGRADE);
    if (HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(upgrade)) {
      WebSocketServerHandshakerFactory wsFactory =
          new WebSocketServerHandshakerFactory(req.getUri(), null, false);
      WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
      if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
      } else {
        ChannelFuture future = handshaker.handshake(ctx.channel(), req);
        future.addListener(
            f -> {
              this.configurator.switchToWebSockets(ctx.pipeline());
            });
      }
    } else {
      ReferenceCountUtil.retain(msg);
      this.configurator.switchToPlainHttp(ctx.pipeline());
      ChannelHandlerContext agg = ctx.pipeline().context(HttpObjectAggregator.class);
      agg.fireChannelRead(msg);
    }
  }
コード例 #14
0
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
    String request = packet.content().toString(CharsetUtil.UTF_8);
    if (logger.isDebugEnabled())
      logger.debug("Sender " + packet.sender() + " sent request:" + request);

    if (!sessionList.inverse().containsKey(packet.sender())) {
      String session = UUID.randomUUID().toString();
      String localAddress = ctx.channel().localAddress().toString();
      String remoteAddress = ctx.channel().remoteAddress().toString();
      SubscriptionManagerFactory.getInstance()
          .add(session, session, outputType, localAddress, remoteAddress);
      sessionList.put(session, packet.sender());
      if (logger.isDebugEnabled())
        logger.debug("Added Sender " + packet.sender() + ", session:" + session);
      ctx.channel()
          .writeAndFlush(
              new DatagramPacket(
                  Unpooled.copiedBuffer(
                      Util.getWelcomeMsg().toString() + "\r\n", CharsetUtil.UTF_8),
                  packet.sender()));
    }

    Map<String, Object> headers = getHeaders(sessionList.inverse().get(packet.sender()));
    producer.sendBodyAndHeaders(request, headers);
  }
コード例 #15
0
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable t) {

    Channel ch = ctx.channel();

    // Prevent recursion when the client close the connection during a write operation. In that
    // scenario the sendError will be invoked, but will fail since the channel has already been
    // closed
    // For an unknown reason,
    if (ch.attr(ATTACHMENT) != null
        && Error.class.isAssignableFrom(ch.attr(ATTACHMENT).get().getClass())) {
      return;
    }

    Throwable cause = t.getCause();
    if (cause instanceof TooLongFrameException) {
      sendError(ctx, BAD_REQUEST, null);
      return;
    }

    ch.attr(ATTACHMENT).set(new Error());
    if (ch.isOpen()) {
      sendError(ctx, INTERNAL_SERVER_ERROR, null);
    }

    if (ctx.channel().isActive()) {
      sendError(ctx, INTERNAL_SERVER_ERROR, null);
    }
  }
コード例 #16
0
 @Override
 public void channelInactive(ChannelHandlerContext ctx) throws Exception {
   LOGGER.debug(
       String.format("[%s]\n========关闭连接=======", ctx.channel().localAddress().toString()));
   LOGGER.debug(ctx.channel().remoteAddress().toString());
   LOGGER.debug(ctx.channel().attr(AttributeKey.valueOf("haha")).get().toString());
 }
コード例 #17
0
 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
   if (msg instanceof List) {
     @SuppressWarnings("unchecked")
     List<ResponseWrapper> responses = (List<ResponseWrapper>) msg;
     if (isDebugEnabled) {
       // for performance trace
       LOGGER.debug(
           "receive response list from server: "
               + ctx.channel().remoteAddress()
               + ",list size is:"
               + responses.size());
     }
     client.putResponses(responses);
   } else if (msg instanceof ResponseWrapper) {
     ResponseWrapper response = (ResponseWrapper) msg;
     if (isDebugEnabled) {
       // for performance trace
       LOGGER.debug(
           "receive response list from server: "
               + ctx.channel().remoteAddress()
               + ",request is:"
               + response.getRequestId());
     }
     client.putResponse(response);
   } else {
     LOGGER.error("receive message error,only support List || ResponseWrapper");
     throw new Exception("receive message error,only support List || ResponseWrapper");
   }
 }
コード例 #18
0
 /**
  * 取代netty3.0中的channelConnected()
  *
  * @param ctx
  * @throws Exception
  */
 @Override
 public void channelActive(ChannelHandlerContext ctx) throws Exception {
   //		super.channelActive(ctx);
   handlerDispatcher.addChannel(ctx.channel());
   handlerDispatcher.getMessageQueueHandler().addMessageQueue(ctx.channel()); // 存入对应客户端获取的消息队列
   logger.info("[" + ctx.channel().remoteAddress() + "] : is active......");
   System.out.println("[" + ctx.channel().remoteAddress() + "] : is active......");
 }
コード例 #19
0
 // 暴力停止某个终端,其他终端都会收到离开的信息
 @Override
 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // (3)
   Channel incoming = ctx.channel();
   for (Channel channel : channels) {
     channel.writeAndFlush("[SERVER] - " + incoming.remoteAddress() + " 离开\n");
   }
   channels.remove(ctx.channel());
 }
コード例 #20
0
 /**
  * Completes the request by closing the request and network channel (if {@code
  * closeNetworkChannel} is {@code true}). May also close the channel if the class internally is
  * forcing a close (i.e. if {@link #close()} is called.
  *
  * @param closeNetworkChannel network channel is closed if {@code true}.
  */
 private void completeRequest(boolean closeNetworkChannel) {
   if ((closeNetworkChannel || forceClose) && ctx.channel().isOpen()) {
     writeFuture.addListener(ChannelFutureListener.CLOSE);
     logger.trace("Requested closing of channel {}", ctx.channel());
   }
   closeRequest();
   responseComplete = true;
 }
コード例 #21
0
 @Override
 public void messageReceived(ChannelHandlerContext context, LoginRequest message)
     throws Exception {
   if (context.channel().isOpen()) {
     Castlewood.getServiceManager()
         .getService(LoginService.class)
         .push(new ChannelRequest<>(context.channel(), message));
   }
 }
コード例 #22
0
 @Override
 public void channelInactive(ChannelHandlerContext ctx) throws Exception {
   RedisConnection connection = RedisConnection.getFrom(ctx.channel());
   if (!connection.isClosed()) {
     EventLoopGroup group = ctx.channel().eventLoop().parent();
     reconnect(group, connection);
   }
   ctx.fireChannelInactive();
 }
コード例 #23
0
  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    final Channel inboundChannel = ctx.channel();

    // Start the connection attempt.
    Bootstrap bootstrap = new Bootstrap();
    bootstrap
        .group(inboundChannel.eventLoop())
        .channel(ctx.channel().getClass())
        .handler(
            new ChannelInitializer<SocketChannel>() {
              @Override
              public void initChannel(SocketChannel ch) throws Exception {
                // Create a default pipeline implementation.
                ChannelPipeline pipeline = ch.pipeline();

                // add logging
                if (logger.isDebugEnabled()) {
                  pipeline.addLast("logger", new LoggingHandler("                -->"));
                }

                // add HTTPS proxy -> server support
                if (secure) {
                  SSLEngine engine = SSLFactory.sslContext().createSSLEngine();
                  engine.setUseClientMode(true);
                  pipeline.addLast("proxy -> server ssl", new SslHandler(engine));
                }

                // add handler
                pipeline.addLast(
                    new ProxyRelayHandler(
                        inboundChannel,
                        bufferedCapacity,
                        new RequestInterceptor(),
                        "                -->"));
              }
            })
        .option(ChannelOption.AUTO_READ, false);
    ChannelFuture channelFuture = bootstrap.connect(remoteSocketAddress);
    outboundChannel = channelFuture.channel();
    channelFuture.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
              channelBuffer.clear();
              bufferedMode = bufferedCapacity > 0;
              flushedBuffer = false;
              // connection complete start to read first data
              inboundChannel.read();
            } else {
              // Close the connection if the connection attempt has failed.
              inboundChannel.close();
            }
          }
        });
  }
コード例 #24
0
 @Override
 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { // (3)
   Channel incoming = ctx.channel();
   for (Channel channel : sChannels) {
     channel.writeAndFlush(
         new TextWebSocketFrame("[SERVER] - " + incoming.remoteAddress() + " 离开"));
   }
   System.out.println("Client:" + incoming.remoteAddress() + "离开");
   sChannels.remove(ctx.channel());
 }
コード例 #25
0
 @Override
 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
   if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
     ctx.pipeline().remove(HttpRequestHandler.class);
     group.writeAndFlush(new TextWebSocketFrame("Client " + ctx.channel() + " joined!"));
     group.add(ctx.channel());
   } else {
     super.userEventTriggered(ctx, evt);
   }
 }
コード例 #26
0
  @Override
  public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    ChannelFuture f = null;

    if (null != policyFile) {
      f = ctx.channel().writeAndFlush(policyFile);
    } else {
      f = ctx.channel().writeAndFlush(this.getPolicyFileContents());
    }
    f.addListener(ChannelFutureListener.CLOSE);
  }
コード例 #27
0
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
   if (cause instanceof IOException) {
     ctx.channel().close();
     return;
   }
   logger.error(cause.getMessage(), cause.getCause());
   if (ctx.channel().isOpen()) {
     ctx.channel().close();
   }
 }
コード例 #28
0
ファイル: ChannelUtils.java プロジェクト: rhusar/infinispan
  /**
   * Push a cache entry value out onto the websocket channel (to the browser).
   *
   * @param key The cache entry key whose value is to be pushed to the browser.
   * @param cache The cache containing the key.
   * @param ctx The channel context associated with the browser websocket channel..
   */
  public static void pushCacheValue(
      String key, Cache<Object, Object> cache, ChannelHandlerContext ctx) {
    Object value = cache.get(key);

    JsonObject responseObject = toJSON(key, value, cache.getName());

    // Write the JSON response out onto the channel...
    ctx.channel()
        .writeAndFlush(
            new TextWebSocketFrame(responseObject.toString()), ctx.channel().voidPromise());
  }
コード例 #29
0
 @Override
 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
   MDC.put("channel", String.format("[id: 0x%08x]", ctx.channel().hashCode()));
   if (evt instanceof IdleStateEvent) {
     LOGGER.error(
         "Idle connection ({}). PDUs received: {}",
         ctx.channel().remoteAddress(),
         this.amountOfResponsesReceived);
   }
   super.userEventTriggered(ctx, evt);
 }
コード例 #30
0
  private void write(XHROptionsMessage msg, ChannelHandlerContext ctx, ChannelPromise promise) {
    HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);

    HttpHeaders.addHeader(res, "Set-Cookie", "io=" + msg.getSessionId());
    HttpHeaders.addHeader(res, CONNECTION, KEEP_ALIVE);
    HttpHeaders.addHeader(res, ACCESS_CONTROL_ALLOW_HEADERS, CONTENT_TYPE);
    addOriginHeaders(ctx.channel(), res);

    ByteBuf out = encoder.allocateBuffer(ctx.alloc());
    sendMessage(msg, ctx.channel(), out, res, promise);
  }