liurunyu
2024-08-15 f7e731bdc2fce4445c0d22993134c6c2b07d207b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.ruoyi.common.utils.netty;
 
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
 
 
/**
 * @author 86175
 */
@Slf4j
public class connectToClient {
 
 
    public static void write2Client(final String receiveStr, Channel ctx, final String mark) {
 
        try {
            //netty需要用ByteBuf传输
            ByteBuf bufff = Unpooled.buffer();
            //对接需要16进制
            bufff.writeBytes(ConvertCode.hexString2Bytes(receiveStr));
            // throws Exception
            ctx.writeAndFlush(bufff).addListener(
                    (ChannelFutureListener) future -> {
 
                        StringBuilder sb = new StringBuilder();
                        if (!StringUtils.isEmpty(mark)) {
                            sb.append("【").append(mark).append("】");
                        }
                        if (future.isSuccess()) {
                            log.info(sb + "回写成功" + receiveStr);
                        } else {
                            log.error(sb + "回写失败" + receiveStr);
                        }
                    }
 
            );
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用通用writeToClient()异常" + e.getMessage());
            log.error("调用通用writeToClient()异常:", e);
        }
    }
 
}