jiazx0107
2025-09-01 ce4f9b9f72a4269a1f25812dadd59bfb92c7b3cf
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.ld.io.netty;
 
import com.ld.io.api.InvokeResult;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class NettyChannel {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private ChannelHandlerContext ctx;
 
    NettyChannel(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }
 
    public ChannelHandlerContext getCtx() {
        return ctx;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
 
        NettyChannel that = (NettyChannel) o;
 
        return ctx.equals(that.ctx);
    }
 
    @Override
    public int hashCode() {
        return ctx.hashCode();
    }
 
    InvokeResult invoke(byte[] bytes) {
        if (ctx == null) {
            return InvokeResult.SOCKET_NOT_CREATE;
        }
 
        if (!ctx.channel().isActive()) {
            ctx.close();
            return InvokeResult.CHANNEL_CLOSED;
        }
 
        ByteBuf buf = Unpooled.copiedBuffer(bytes);
        try {
            ctx.writeAndFlush(buf).sync();
        } catch (Exception e) {
            logger.error("Invoke happened error", e);
            return InvokeResult.SOCKET_STATE_ERROR;
        }
        return InvokeResult.SUCCESS;
    }
 
    public void destroy() {
        try {
            ctx.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}