Advertisement
Dudemister1999

ServerHandler Class

Aug 7th, 2014
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. public class ServerHandler extends ChannelInboundHandlerAdapter
  2. {
  3.  
  4.     @Override
  5.     public void channelRead(ChannelHandlerContext context, Object msg)
  6.     {
  7.         ByteBuf in = (ByteBuf) msg;
  8.         try
  9.         {
  10.             while (in.isReadable())
  11.             {
  12.                 System.out.println((char) in.readByte());
  13.                 System.out.flush();
  14.             }
  15.            
  16.             ByteBuf buf = createBuf(Server.getServerData());
  17.             this.sendBuf(context, buf);
  18.         }
  19.         finally
  20.         {
  21.             ReferenceCountUtil.release(msg);
  22.         }
  23.     }
  24.  
  25.     @Override
  26.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
  27.     {
  28.         cause.printStackTrace();
  29.         ctx.close();
  30.     }
  31.    
  32.     private void sendBuf(ChannelHandlerContext context, ByteBuf buf)
  33.     {
  34.         context.pipeline().firstContext().writeAndFlush(buf).addListener(ChannelFutureListener.CLOSE);
  35.     }
  36.    
  37.     private ByteBuf createBuf(String data)
  38.     {
  39.         ByteBuf buf = Unpooled.buffer();
  40.         buf.writeByte(255);
  41.         char[] characters = data.toCharArray();
  42.         buf.writeShort(characters.length);
  43.         char[] chars = characters;
  44.         int length = characters.length;
  45.  
  46.         for (int i = 0; i < length; ++i)
  47.         {
  48.             char character = chars[i];
  49.             buf.writeChar(character);
  50.         }
  51.  
  52.         return buf;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement