예제 #1
0
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
   Route route = app.getRouter().parseRoute(getUtf(buffer));
   byte[] data = new byte[buffer.readableBytes()];
   buffer.readBytes(data);
   LocalSession localSession = sessions.getSession(ctx.getChannel().getId()).getLocalSession();
   byte[] response = server.handle(route, localSession, data);
   if (response != null) {
     ctx.getChannel().write(response);
   }
 }
예제 #2
0
/** Created with IntelliJ IDEA. User: zhongyuan Date: 13-1-11 Time: 上午1:38 */
public class DefaultRequestHandler extends SimpleChannelUpstreamHandler {
  private Jpomelo app = Jpomelo.instance();
  private Sessions sessions;
  private Server server;
  private String frontendId;

  public DefaultRequestHandler(Sessions sessions, String moduleId, Server server) {
    this.sessions = sessions;
    this.frontendId = moduleId;
    this.server = server;
  }

  @Override
  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    Channel channel = ctx.getChannel();
    sessions.createSession(channel.getId(), frontendId, channel);
  }

  @Override
  public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    Channel channel = ctx.getChannel();
    if (!sessions.removeSession(channel.getId())) {
      Log.error("删除Session失败! sockId: " + channel.getId());
    }
  }

  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
    Route route = app.getRouter().parseRoute(getUtf(buffer));
    byte[] data = new byte[buffer.readableBytes()];
    buffer.readBytes(data);
    LocalSession localSession = sessions.getSession(ctx.getChannel().getId()).getLocalSession();
    byte[] response = server.handle(route, localSession, data);
    if (response != null) {
      ctx.getChannel().write(response);
    }
  }

  private String getUtf(ChannelBuffer buffer) {
    // UTF = short + data;
    int readableBytes = buffer.readableBytes();
    if (readableBytes < 2) {
      throw new IllegalArgumentException("buffer doesn't contains utf data!");
    }

    // 只有长度 没有内容
    if (readableBytes == 2) {
      return "";
    }

    int dataLen = buffer.readUnsignedShort();
    byte[] data = new byte[dataLen];
    buffer.readBytes(data);

    try {
      return new String(data, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      Log.error("解码UTF错误", e);
    }

    return null;
  }
}