Netty向设备发送消息并等待设备响应

在使用netty开发和硬件对接时,经常会遇到服务端给硬件设备发送命令后需要等待设备反馈响应命令后执行逻辑。

一、定义同步等待

/**
 * @author: 晨光
 * @description: 同步等待
 * @Version 1.0
 */
public class SyncPromise {

    // 用于接收结果
    private BaseMessageInfoVo messageResponse;

    //CountDownLatch可以看作是一个计数器,当计数器的值减到0时,所有等待的线程将被释放并继续执行。
    private final CountDownLatch countDownLatch = new CountDownLatch(1);

    // 用于判断是否超时
    private boolean isTimeout = false;

    /**
     * 同步等待返回结果
     * timeout 超时时间    unit 时间单位
     */
    public BaseMessageInfoVo get(long timeout, TimeUnit unit) throws InterruptedException {
        // 等待阻塞,超时时间内countDownLatch减到0,将提前唤醒,以此作为是否超时判断
        // 如果在指定时间内计数器仍未归零,则返回false,否则返回true。
        boolean earlyWakeUp = countDownLatch.await(timeout, unit);

        if(earlyWakeUp) {
            // 超时时间内countDownLatch减到0,提前唤醒,说明已有结果
            return messageResponse;
        } else {
            // 超时时间内countDownLatch没有减到0,自动唤醒,说明超时时间内没有等到结果
            isTimeout = true;
            return null;
        }
    }
    // 计数器清零,唤醒
    public void wake() {
        countDownLatch.countDown();
    }

    public BaseMessageInfoVo getMessageResponse() {
        return messageResponse;
    }

    public void setMessageResponse(BaseMessageInfoVo messageResponse) {
        this.messageResponse = messageResponse;
    }

    public boolean isTimeout() {
        return isTimeout;
    }
}

2、定义工具类发送同步消息

/**
 * @author: 晨光
 * @description: 定义工具类
 * @Version 1.0
 */
public class SyncUtil {

    private final static Map<String, SyncPromise> syncPromiseMap =  new ConcurrentHashMap<>();
    //key 唯一主键类,方便在处理逻辑中找到唤醒
    public static BaseMessageInfoVo send(String key,Channel channel,BaseMessageInfoVo messageRequest, long timeout, TimeUnit unit) throws Exception{

        if(channel == null) {
            throw new NullPointerException("channel");
        }

        if(messageRequest == null) {
            throw new NullPointerException("rpcRequest");
        }

        if(timeout <= 0) {
            throw new IllegalArgumentException("timeout must greater than 0");
        }

        // 创造一个容器,用于存放当前线程与rpcClient中的线程交互
        SyncPromise syncPromise = new SyncPromise();
        syncPromiseMap.put(key, syncPromise);

        // 发送消息,此处如果发送玩消息并且在get之前返回了结果,下一行的get将不会进入阻塞,也可以顺利拿到结果
        channel.writeAndFlush(messageRequest);

        // 等待获取结果
        BaseMessageInfoVo messageResponse = syncPromise.get(timeout, unit);

        if(messageResponse == null) {
            if(syncPromise.isTimeout()) {
                throw new TimeoutException("等待响应结果超时");
            } else{
                throw new Exception("其他异常");
            }
        }

        // 移除容器
        syncPromiseMap.remove(header+ ChannelMap.getEquipCode(channel));

        return messageResponse;
    }

    public static Map<String, SyncPromise> getSyncPromiseMap(){
        return syncPromiseMap;
    }
}

通过上面的类即可同步向设备发送命令。

3、在设备返回命令的逻辑中对应唤醒处理逻辑

/**
 * 连接管理 handler
 */
@Slf4j
@Service
@ChannelHandler.Sharable
public class SyncRequestHandler extends SimpleChannelInboundHandler<BaseMessageInfoVo> { //ChannelInboundHandlerAdapter


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BaseMessageInfoVo resp) throws Exception {
        
        //查询相应key对应的是否有返回,如果有返回就唤醒,直接返回响应数据
        SyncPromise syncPromise = SyncUtil.getSyncPromiseMap().get(resp.getHeader()+ChannelMap.getEquipCode(ctx.channel()));
        if(syncPromise != null){
            //在获取对象不为null时执行唤醒操作,否则直接丢弃
            syncPromise.setMessageResponse(resp);
            syncPromise.wake();
        }
    }
}

4、具体的调用发送命令处理逻辑

BaseMessageInfoVo responseInfo = SyncUtil.send(MessageConstant.UPGRADE_PREIX, channel, baseMessageInfoVo, 5, TimeUnit.SECONDS);
System.out.println(JSONObject.toJSONString(responseInfo));//根据具体逻辑进行判断
return ApiResult.success(responseInfo.getHeader()+responseInfo.getData(),"发送成功");

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是一个基于Netty的示例代码,可以用于发送HTTP请求并解析响应中的Multipart内容: ```java import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.multipart.HttpDataFactory; import io.netty.handler.codec.http.multipart.HttpPostRequestEncoder; import io.netty.handler.codec.http.multipart.MemoryFileUpload; import io.netty.handler.codec.http.multipart.MemoryAttribute; import io.netty.util.CharsetUtil; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Map; public class NettyHttpClient { private final String host; private final int port; public NettyHttpClient(String host, int port) { this.host = host; this.port = port; } public void sendHttpRequest() throws URISyntaxException, InterruptedException, UnsupportedEncodingException { URI uri = new URI("/upload"); String requestBody = "test request body"; String boundary = "----Boundary"; ByteBuf content = Unpooled.copiedBuffer(requestBody, CharsetUtil.UTF_8); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.toASCIIString(), content); HttpUtil.setKeepAlive(request, true); HttpUtil.setContentLength(request, requestBody.length()); request.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.MULTIPART_FORM_DATA + "; boundary=" + boundary); HttpDataFactory factory = new DefaultHttpDataFactory(false); // Use DefaultHttpDataFactory to write data to disk HttpPostRequestEncoder encoder = new HttpPostRequestEncoder(factory, request, false); encoder.setBodyHttpDatas(List.of( new MemoryAttribute("key1", "value1"), new MemoryAttribute("key2", "value2"), new MemoryFileUpload("file", "filename.txt", "text/plain", null, CharsetUtil.UTF_8, requestBody.getBytes()) )); EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; try { String contentType = response.headers().get(HttpHeaderNames.CONTENT_TYPE); if (contentType != null && contentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString())) { HttpPostMultipartResponseDecoder decoder = new HttpPostMultipartResponseDecoder(factory, boundary); decoder.offer(response.content()); List<InterfaceHttpData> parts = decoder.getBodyHttpDatas(); for (InterfaceHttpData part : parts) { if (part instanceof FileUpload) { FileUpload fileUpload = (FileUpload) part; if (fileUpload.isCompleted()) { System.out.println("Received file: " + fileUpload.getFilename()); System.out.println("Content: " + fileUpload.getString(CharsetUtil.UTF_8)); } } } } else { System.out.println("Received response content: " + response.content().toString(CharsetUtil.UTF_8)); } } catch (Exception e) { e.printStackTrace(); } finally { response.release(); } } else { System.err.println("Unknown message type: " + msg.getClass().getName()); } } }); ChannelFuture future = bootstrap.connect(host, port).sync(); ChannelHandlerContext ctx = future.channel().pipeline().context(ChannelInboundHandlerAdapter.class); HttpContent contentChunk = encoder.readChunk(ctx); while (contentChunk != null) { future.channel().write(contentChunk); contentChunk = encoder.readChunk(ctx); } future.channel().flush(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } } ``` 这个示例代码中,我们首先创建了一个`FullHttpRequest`对象,并根据需要设置了请求头和请求体。然后,我们使用`HttpPostRequestEncoder`将请求体中的数据编码成multipart格式,并将它们添加到请求中。注意,这里我们使用了`MemoryFileUpload`和`MemoryAttribute`,它们将数据存储在内存中而不是磁盘上。 接着,我们创建了一个`Bootstrap`对象,并设置了它的`Handler`。在`Handler`中,我们对服务器返回的响应进行了解析。如果响应的`Content-Type`是multipart格式,我们使用`HttpPostMultipartResponseDecoder`对响应中的数据进行解码,并逐个处理每个part。如果part是一个上传的文件,我们输出它的文件名和内容。否则,我们输出它的文本内容。 最后,我们将编码后的请求发送到服务器,并等待响应。当响应接收完毕后,我们关闭连接并退出程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

StruggleRookie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值