|
|
|
@ -9,6 +9,8 @@ import io.netty.channel.socket.SocketChannel;
|
|
|
|
|
import io.netty.channel.socket.nio.NioSocketChannel;
|
|
|
|
|
import io.netty.handler.codec.MessageToByteEncoder;
|
|
|
|
|
|
|
|
|
|
import java.nio.charset.StandardCharsets;
|
|
|
|
|
|
|
|
|
|
public class SocketUtil {
|
|
|
|
|
private final String host;
|
|
|
|
|
private final int port;
|
|
|
|
@ -32,6 +34,7 @@ public class SocketUtil {
|
|
|
|
|
ChannelPipeline p = ch.pipeline();
|
|
|
|
|
p.addLast(new HexDataEncoder());
|
|
|
|
|
p.addLast(new HexDataSenderHandler(hexData));
|
|
|
|
|
p.addLast(new ClientHandler()); // 添加客户端 Handler
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
@ -46,8 +49,6 @@ public class SocketUtil {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class HexDataSenderHandler extends ChannelInboundHandlerAdapter {
|
|
|
|
|
private final String hexData;
|
|
|
|
|
|
|
|
|
@ -78,9 +79,28 @@ class HexDataSenderHandler extends ChannelInboundHandlerAdapter {
|
|
|
|
|
}
|
|
|
|
|
return data;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static class ClientHandler extends ChannelInboundHandlerAdapter {
|
|
|
|
|
|
|
|
|
|
@Override
|
|
|
|
|
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
|
|
|
|
|
// 处理服务器响应数据
|
|
|
|
|
byte[] bytes = (byte[]) msg;
|
|
|
|
|
String response = new String(bytes, StandardCharsets.US_ASCII);
|
|
|
|
|
System.out.println("Server response: " + response);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class HexDataEncoder extends MessageToByteEncoder<ByteBuf> {
|
|
|
|
|
@Override
|
|
|
|
|
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
|
|
|
|
|
cause.printStackTrace();
|
|
|
|
|
ctx.close();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static class HexDataEncoder extends MessageToByteEncoder<ByteBuf> {
|
|
|
|
|
@Override
|
|
|
|
|
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
|
|
|
|
|
byte[] bytes = new byte[msg.readableBytes()];
|
|
|
|
@ -88,3 +108,5 @@ class HexDataEncoder extends MessageToByteEncoder<ByteBuf> {
|
|
|
|
|
out.writeBytes(bytes);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|