Recently, the project needs to realize Java to send messages to the terminal. The terminal only accepts hexadecimal data. After learning Netty, however, it still fails to send in the development process

1. Set the sent and accepted string formats in the ClientInitializer class

StringDecoder() and StringEncoder() are used to encode, so that the packets received by the terminal cannot be parsed. You need to customize the format of sending and receiving messages, as follows

public class ClientInitializer extends ChannelInitializer<SocketChannel> { private CountDownLatch lathc; public ClientInitializer(CountDownLatch lathc) { this.lathc = lathc; } private ClientHandler handler; @Override protected void initChannel(SocketChannel sc) throws Exception { handler = new ClientHandler(lathc); sc.pipeline().addLast("encoder",new MyEncoder()); Sc.pipeline ().addLast("decoder",new MyDecoder()); // Custom received message format (hexadecimal data) sc.pipeline().addlast (new IdleStateHandler(0, 5, 0, timeUnit.seconds)); sc.pipeline().addLast(new ReadTimeoutHandler(60)); // Set timeout sc.pipeline().addlast (handler); }}Copy the code

2. Customize the sending message format MyEncoder

public class MyEncoder extends MessageToByteEncoder<String> { @Override protected void encode(ChannelHandlerContext channelHandlerContext, String s, ByteBuf ByteBuf) throws Exception {// Convert a hexadecimal string into an array bytebuf. writeBytes(hexString2Bytes(s)); } /** * @param SRC hexadecimal string * @return byte array * @title :hexString2Bytes * @description: hexadecimal string to byte array */ public static byte[] hexString2Bytes(String src) { int l = src.length() / 2; byte[] ret = new byte[l]; for (int i = 0; i < l; i++) { ret[i] = (byte) Integer.valueOf(src.substring(i * 2, i * 2 + 2), 16).byteValue(); } return ret; }}Copy the code

3. Customize the receiving message format MyDecoder

public class MyDecoder extends ByteToMessageDecoder { @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> List) throws Exception {// Create an array of bytes,buffer.readableBytes Bytes [] b = new byte[bytebuf.readableBytes ()]; // Copy the contents to the byte array b bytebuf.readbytes (b); list.add(bytesToHexString(b)); } public String bytesToHexString(byte[] bArray) { StringBuffer sb = new StringBuffer(bArray.length); String sTemp; for (int i = 0; i < bArray.length; i++) { sTemp = Integer.toHexString(0xFF & bArray[i]); if (sTemp.length() < 2) sb.append(0); sb.append(sTemp.toUpperCase()); } return sb.toString(); } public static String toHexString1(byte[] b) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < b.length; ++i) { buffer.append(toHexString1(b[i])); } return buffer.toString(); } public static String toHexString1(byte b) { String s = Integer.toHexString(b & 0xFF); if (s.length() == 1) { return "0" + s; } else { return s; }}}Copy the code