#
whycq
2024-08-14 a5259c5238cf07b9a51b429a144eeac21864159e
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package com.example.agvcontroller.socket;
 
import java.nio.charset.StandardCharsets;
 
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import android.util.Log;
 
import com.example.agvcontroller.Item;
import com.example.agvcontroller.protocol.AgvAction;
 
 
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
 
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
 
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
 
    private static final String TAG = "NettyServerHandler";
    private static ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<>();
 
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String clientId = ctx.channel().remoteAddress().toString();
        channelMap.put(clientId, ctx.channel());
        EventBus.getDefault().post(new Item("1",clientId,"3"));
        Log.d(TAG, "Client connected: " + clientId);
    }
 
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String clientId = ctx.channel().remoteAddress().toString();
        channelMap.remove(clientId);
        EventBus.getDefault().post(clientId);
        Log.d(TAG, "Client disconnected: " + clientId);
    }
 
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 处理接收到的消息
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            while (byteBuf.isReadable()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(bytes);
                String hexString = bytesToHex(bytes);
                // 获取agv信息 添加到list中
                Log.d(TAG, "ctx: " + ctx.channel().remoteAddress().toString() );
                Log.d(TAG, "Received: " + hexString);
            }
        } finally {
            byteBuf.release();
        }
    }
 
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
    // 将十六进制字符串转换为字节数组
    private byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
 
    public static void sendMessageToClient(String clientId, byte[] message) {
        Channel channel = channelMap.get(clientId);
        if (channel != null && channel.isActive()) {
            ByteBuf buf = Unpooled.wrappedBuffer(message);
            String upperCase = ByteBufUtil.hexDump(buf).toUpperCase();
            Log.d(TAG, "upperCase " + upperCase);
            channel.writeAndFlush(buf);
        } else {
            Log.d(TAG, "Client " + clientId + " is not connected");
        }
    }
 
    public static void sendMessageToClient(String clientId, AgvAction<?> action) {
 
 
 
        Channel channel = channelMap.get(clientId);
        if (channel != null && channel.isActive()) {
 
            channel.writeAndFlush(action);
        } else {
            Log.d(TAG, "Client " + clientId + " is not connected");
        }
    }
 
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
 
}