Advertisement
Guest User

Untitled

a guest
Apr 26th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. package org.rse.network;
  2.  
  3. import io.netty.channel.ChannelHandlerAdapter;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.channel.ChannelPromise;
  6. import io.netty.handler.timeout.IdleStateEvent;
  7.  
  8. import java.io.IOException;
  9.  
  10. import org.rse.model.mortals.players.Player;
  11. import org.rse.network.codec.Message;
  12.  
  13. public final class ChannelHandler extends ChannelHandlerAdapter {
  14.  
  15.     private Player player;
  16.  
  17.     @Override
  18.     public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
  19.         if (player != null) {
  20.             player.destroy();
  21.             player = null;
  22.         }
  23.         super.disconnect(ctx, promise);
  24.     }
  25.  
  26.     @Override
  27.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  28.         handleEvent(ctx, msg);
  29.         ctx.fireChannelRead(msg);
  30.     }
  31.  
  32.     @Override
  33.     public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
  34.         handleEvent(ctx, evt);
  35.         super.userEventTriggered(ctx, evt);
  36.     }
  37.  
  38.     @Override
  39.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  40.         if (cause != null && !(cause instanceof IOException))
  41.             cause.printStackTrace();
  42.         ctx.channel().close();
  43.         super.exceptionCaught(ctx, cause);
  44.     }
  45.  
  46.     private void handleEvent(ChannelHandlerContext ctx, Object msg) {
  47.         if (msg == null)
  48.             System.err.println("Invalid message received!");
  49.         else {
  50.             if (msg instanceof Player) {
  51.                 if (player != null)
  52.                     System.err.println("A player already exists for this channel!");
  53.                 else
  54.                     player = (Player) msg;
  55.             } else if (msg instanceof Message) {
  56.                 if (player == null)
  57.                     System.err.println("Player does not exist for message received!");
  58.                 else
  59.                     player.queuePacket((Message) msg);
  60.             } else if (msg instanceof IdleStateEvent)
  61.                 ctx.close();
  62.         }
  63.     }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement