netty发送接收16进制代码_java netty与c++使用socket tcp协议通信,c++作为客户端,java作为服务端使用的是netty,接收字节数据,先将字节转16进制字符串再转为普通字...

通过重写channelRead(ChannelHandler ctx, Object msg) 方法读取c++发过来的字节数据。

public class ServerHandler extends ChannelHandlerAdapter{

public void channelRead(ChannelHandlerContext channel, Object msg) throws Exception {

try {

ByteBuf buf = (ByteBuf)msg;

byte [] bytes = new byte[buf.readableBytes()];

buf.readBytes(bytes);//复制内容到字节数组bytes

String hex = bytes2HexString(bs); //将byte数组转为16进制字符串

String str = hexString2String(hex,”GBK”); //将16进制字符串转换为普通字符串

System.out.println(str); //这里打印全是乱码

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

log.error(“异常:”,e);

}

}

private String bytes2HexString(byte[] b) {

StringBuffer result = new StringBuffer();

String hex;

for (int i = 0; i < b.length; i&#

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
,我们需要在Spring Boot项目中引入Netty的依赖: ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.22.Final</version> </dependency> ``` 然后,我们需要编写一个Netty客户端类,用于连接服务器并发送16进制数据: ```java public class NettyClient { private final String host; private final int port; private Channel channel; public NettyClient(String host, int port) { this.host = host; this.port = port; } public void connect() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HexEncoder()); pipeline.addLast(new NettyClientHandler()); } }); ChannelFuture future = bootstrap.connect(host, port).sync(); channel = future.channel(); channel.closeFuture().sync(); } finally { group.shutdownGracefully(); } } public void sendHexData(String hexData) { if (channel == null || !channel.isActive()) { throw new IllegalStateException("Connection is not active"); } channel.writeAndFlush(Unpooled.copiedBuffer(hexData, CharsetUtil.US_ASCII)); } } ``` 在上面的代码中,我们使用了HexEncoder类来将字符串换为16进制数据,然后将它们发送到服务器。我们还使用NettyClientHandler类来处理从服务器接收到的响应。 最后,我们可以在Spring Boot应用程序中使用这个Netty客户端类来发送16进制数据: ```java @RestController @RequestMapping("/api") public class NettyController { @GetMapping("/sendHexData") public String sendHexData(@RequestParam String hexData) throws Exception { NettyClient client = new NettyClient("localhost", 8080); client.connect(); client.sendHexData(hexData); return "OK"; } } ``` 在上面的代码中,我们可以使用sendHexData方法来发送16进制数据到服务器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值