NettyChannelInitializer.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.yx.face.netty_client;
  2. import io.netty.channel.ChannelHandler;
  3. import io.netty.channel.ChannelInitializer;
  4. import io.netty.channel.socket.SocketChannel;
  5. import io.netty.handler.codec.string.StringDecoder;
  6. import io.netty.handler.codec.string.StringEncoder;
  7. import lombok.extern.slf4j.Slf4j;
  8. import java.nio.charset.Charset;
  9. import java.util.concurrent.CountDownLatch;
  10. /**
  11. * @ProjectName: face-server
  12. * @Package: com.yx.face.netty
  13. * @ClassName: ServerChannelInitializer
  14. * @Author: 崔哥
  15. * @Description: Netty服务端初始化器
  16. * @Date: 2021/11/22 11:35
  17. * @Version: 1.0
  18. */
  19. @Slf4j
  20. public class NettyChannelInitializer extends ChannelInitializer<SocketChannel> {
  21. private String response;
  22. private CountDownLatch countDownLatch;
  23. private String param;
  24. private RequestClientHandler requestClientHandler;
  25. public NettyChannelInitializer(String param) {
  26. this.param = param;
  27. }
  28. @Override
  29. protected void initChannel(SocketChannel socketChannel) throws Exception {
  30. countDownLatch = new CountDownLatch(1);
  31. requestClientHandler = new RequestClientHandler(param, this);
  32. socketChannel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
  33. socketChannel.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
  34. socketChannel.pipeline().addLast((ChannelHandler) requestClientHandler);
  35. }
  36. public String getResponse() {
  37. try {
  38. if (null != countDownLatch) {
  39. countDownLatch.await();
  40. }
  41. } catch (InterruptedException exception) {
  42. exception.printStackTrace();
  43. }
  44. return response;
  45. }
  46. // 用于设置响应结果,并且做countDown操作,通知请求线程
  47. public void setResponse(String response) {
  48. this.response = response;
  49. countDownLatch.countDown();
  50. }
  51. }