nio~ByteOrder

本文介绍了Java NIO中ByteOrder的基本概念及其使用方法。详细解释了如何改变字节顺序并提供了一个简单的示例程序来展示不同字节顺序下短整型数的存储方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

*ByteOrder定义了写入buffer时字节的顺序

---java默认是big-endian

*API

---2个内置的ByteOrder

ByteOrder.BIG_ENDIAN和ByteOrder.LITTLE_ENDIAN

---ByteOrder.nativeOrder()

返回本地jvm运行的硬件的字节顺序.使用和硬件一致的字节顺序可能使buffer更加有效.

---ByteOrder.toString()

返回ByteOrder的名字,BIG_ENDIAN或LITTLE_ENDIAN

*示例

ByteOrder测试/**
 * Feb 25, 2011 by dzh
 */
package buffer.endian;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * @author dzh
 *
 */
public class ByteOrderTest {
	public static void main(String[] args) {
		ByteBuffer buf =ByteBuffer.allocate(4);
		System.out.println("Default java endian: "+buf.order().toString()); 
		
		buf.putShort((short) 1);
		buf.order(ByteOrder.LITTLE_ENDIAN);
		System.out.println("Now: "+buf.order().toString());
		buf.putShort((short) 2);
		
		buf.flip();
		for(int i=0;i<buf.limit();i++)
			System.out.println(buf.get()&0xFF); 
		
		System.out.println("My PC: "+ByteOrder.nativeOrder().toString());
	}
}

//结果
Default java endian: BIG_ENDIAN
Now: LITTLE_ENDIAN
0
1
2
0
My PC: LITTLE_ENDIAN

转载于:https://www.cnblogs.com/bronte/articles/1965167.html

### 使用 Netty 实现 NIO 编程 Netty 是一个基于 Java NIO 的框架,能够帮助开发者快速构建高性能、高可靠性的网络应用程序。通过 Netty,可以利用非阻塞 IO 方式来处理多个客户端连接,并且支持异步事件驱动机制[^2]。 下面展示了一个简单的 Netty 客户端和服务端的实现示例: #### 服务端代码 以下是使用 Netty 构建的服务端代码示例,该示例展示了如何监听来自客户端的消息并返回响应。 ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class NettyServer { private int port; public NettyServer(int port) { this.port = port; } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); // 负责接收连接请求 EventLoopGroup workerGroup = new NioEventLoopGroup(); // 负责处理已建立的连接 try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeServerHandler()); // 自定义处理器 } }); ChannelFuture f = b.bind(port).sync(); // 绑定端口并同步等待完成 System.out.println("服务器启动成功,端口号:" + port); f.channel().closeFuture().sync(); // 阻塞当前线程直到通道关闭 } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8080; // 设置端口号 new NettyServer(port).run(); } } ``` #### 处理器代码 自定义处理器 `TimeServerHandler` 可以用来处理接收到的数据包以及发送回执消息给客户端。 ```java import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; public class TimeServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8").trim(); System.out.println("接收到客户端消息:" + body); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? java.time.LocalDateTime.now().toString() : "BAD REQUEST"; ByteBuf resp = getByteBuf(ctx, currentTime); ctx.writeAndFlush(resp); // 将响应写入到管道中并发往远程节点 } private ByteBuf getByteBuf(ChannelHandlerContext ctx, String currentTime) { byte[] bytes = currentTime.getBytes(java.nio.charset.StandardCharsets.UTF_8); ByteBuf buffer = ctx.alloc().buffer(bytes.length); buffer.writeBytes(bytes); return buffer; } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); // 发生异常时关闭上下文对象 } } ``` #### 客户端代码 这是对应的客户端代码片段,用于向上述服务端发起请求并打印其反馈的结果。 ```java import io.netty.bootstrap.Bootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; public class NettyClient { public static void main(String[] args) throws InterruptedException { String host = "localhost"; int port = 8080; EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ClientInitializer()); ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().closeFuture().sync(); } catch (Exception e){ e.printStackTrace(); }finally{ group.shutdownGracefully(); } } } class ClientInitializer extends io.netty.channel.ChannelInitializer<NioSocketChannel> { @Override protected void initChannel(NioSocketChannel ch) throws Exception { ch.pipeline().addLast(new TimeClientHandler()); } } class TimeClientHandler extends io.netty.channel.SimpleChannelInboundHandler<Object> { @Override public void channelActive(io.netty.channel.ChannelHandlerContext ctx) throws Exception { final ByteBuf timeReqBuffer = getTimeRequestBuffer(ctx); ctx.writeAndFlush(timeReqBuffer); } private ByteBuf getTimeRequestBuffer(io.netty.channel.ChannelHandlerContext ctx) { String requestString = "QUERY TIME ORDER"; ByteBuf buffer = ctx.alloc().buffer(requestString.getBytes().length); buffer.writeBytes(requestString.getBytes()); return buffer; } @Override protected void channelRead0(io.netty.channel.ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf)msg; byte[] responseArray = new byte[buf.readableBytes()]; buf.readBytes(responseArray); String serverResponse = new String(responseArray,"UTF-8"); System.out.println("服务器时间:" + serverResponse); } @Override public void exceptionCaught(io.netty.channel.ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } } ``` 以上代码分别实现了 Netty 的服务端和客户端逻辑,涵盖了基本的功能需求。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值