12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package com.yx.face.netty_client;
- import io.netty.channel.ChannelHandler;
- import io.netty.channel.ChannelInitializer;
- import io.netty.channel.socket.SocketChannel;
- import io.netty.handler.codec.string.StringDecoder;
- import io.netty.handler.codec.string.StringEncoder;
- import lombok.extern.slf4j.Slf4j;
- import java.nio.charset.Charset;
- import java.util.concurrent.CountDownLatch;
- /**
- * @ProjectName: face-server
- * @Package: com.yx.face.netty
- * @ClassName: ServerChannelInitializer
- * @Author: 崔哥
- * @Description: Netty服务端初始化器
- * @Date: 2021/11/22 11:35
- * @Version: 1.0
- */
- @Slf4j
- public class NettyChannelInitializer extends ChannelInitializer<SocketChannel> {
- private String response;
- private CountDownLatch countDownLatch;
- private String param;
- private RequestClientHandler requestClientHandler;
- public NettyChannelInitializer(String param) {
- this.param = param;
- }
- @Override
- protected void initChannel(SocketChannel socketChannel) throws Exception {
- countDownLatch = new CountDownLatch(1);
- requestClientHandler = new RequestClientHandler(param, this);
- socketChannel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
- socketChannel.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
- socketChannel.pipeline().addLast((ChannelHandler) requestClientHandler);
- }
- public String getResponse() {
- try {
- if (null != countDownLatch) {
- countDownLatch.await();
- }
- } catch (InterruptedException exception) {
- exception.printStackTrace();
- }
- return response;
- }
- // 用于设置响应结果,并且做countDown操作,通知请求线程
- public void setResponse(String response) {
- this.response = response;
- countDownLatch.countDown();
- }
- }
|