Advertisement
Guest User

Untitled

a guest
Jun 18th, 2021
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. import io.netty.channel.Channel;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.SimpleChannelInboundHandler;
  4.  
  5. import java.util.concurrent.BlockingQueue;
  6. import java.util.concurrent.LinkedBlockingQueue;
  7.  
  8. public class T2Handler extends SimpleChannelInboundHandler<T2Packet> {
  9.  
  10.     private Channel channel;
  11.     private final BlockingQueue<T2Packet> packetsQueue = new LinkedBlockingQueue<>();
  12.     private boolean destabilised = false;
  13.  
  14.     public T2Handler(boolean client) {
  15.         Thread thread = new Thread(() -> {
  16.             try {
  17.                 T2Packet p;
  18.                 while (!destabilised) {
  19.                     p = packetsQueue.take();
  20.                     System.out.println(p);
  21.                     if (!client)send(new T2Packet(p.getId(), p.getValue()+1, "t2 answer "+p.getName()));
  22.                 }
  23.             }catch (Exception e){
  24.                 e.printStackTrace();
  25.             }
  26.         });
  27.         thread.setDaemon(true);
  28.         thread.start();
  29.     }
  30.  
  31.     public void send(T2Packet packet){
  32.         channel.writeAndFlush(packet);
  33.     }
  34.  
  35.     @Override
  36.     public void channelActive(ChannelHandlerContext ctx) throws Exception {
  37.         channel = ctx.channel();
  38.         super.channelActive(ctx);
  39.     }
  40.  
  41.     @Override
  42.     protected void channelRead0(ChannelHandlerContext ctx, T2Packet msg) throws Exception {
  43.         packetsQueue.offer( msg);
  44.     }
  45.  
  46.     @Override
  47.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  48.         destabilised = true;
  49.         super.exceptionCaught(ctx, cause);
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement