Ejemplo n.º 1
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);
    }
  }
Ejemplo n.º 2
0
 private NettyMessage buildResponse(byte result) {
   NettyMessage message = new NettyMessage();
   Header header = new Header();
   header.setType(MessageType.LOGIN_RESP.value());
   message.setHeader(header);
   message.setBody(result);
   return message;
 }