JAVA 之 NIO小示例

本文介绍了一个使用 Java NIO 技术实现的服务端程序示例,演示了如何通过 ByteBuffer 进行数据的读取与处理,并展示了如何利用 ServerSocketChannel 和 Selector 实现非阻塞式的网络通信。

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

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;


public class ByteBufferTest {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		ByteBuffer buf = ByteBuffer.allocate(256);
		
		while(true) {
			int c = System.in.read();
			
			if(c==-1) {
				break;
			}
			
			buf.put((byte)c);
			
			if(c=='\n') {
				//调用flip()使limit变为当前的position的值,position的值变为0
				//为接下来从ByteBuffer读取做准备
				buf.flip();
				
				byte[] content = new byte[buf.limit()];
				
				//从ByteBuffer中读取数据到byte数组中
				buf.get(content);
				
				System.out.println(new String(content));
				System.out.println();
				//position=0 , limit=capacity
				//为写入数据到ByteBuffer中做准备
				buf.clear();
			}
			
//			ScatteringByteChannel sbc = new ScatteringByteChannel() {
//				
//				@Override
//				public boolean isOpen() {
//					// TODO Auto-generated method stub
//					return false;
//				}
//				
//				@Override
//				public void close() throws IOException {
//					// TODO Auto-generated method stub
//					
//				}
//				
//				@Override
//				public int read(ByteBuffer arg0) throws IOException {
//					// TODO Auto-generated method stub
//					return 0;
//				}
//				
//				@Override
//				public long read(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
//					// TODO Auto-generated method stub
//					return 0;
//				}
//				
//				@Override
//				public long read(ByteBuffer[] arg0) throws IOException {
//					// TODO Auto-generated method stub
//					return 0;
//				}
//			};
		}
		
		
	}
	
	private static void acceptConnections(int port) throws IOException {
		
		//打开一个selector
		Selector acceptSelector = SelectorProvider.provider().openSelector();
		
		//SelectableChannel子类
		ServerSocketChannel ssc = ServerSocketChannel.open();
		//将其设置为 non-blocking状态,这样才能进行异步IO操作
		ssc.configureBlocking(false);
		
		//给ServerSocketChannel对应的socket绑定IP和端口
		InetAddress  ia = InetAddress.getLocalHost();
		InetSocketAddress isa = new InetSocketAddress(ia,port);
		
		ssc.socket().bind(isa);
		
		//将ServerSocketChannel注册到Selector上,返回对应的SelectionKey
		SelectionKey acceptKey = ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
		
		int keysAdded = 0;
		
		//用select()函数来监控注册在Selector上的SelectableChannel
		//返回值代表了有多少channel可以进行IO操作(ready for IO)
		
		while((keysAdded=acceptSelector.select())>0) {
			//selectedKeys()返回一个SelectionKey的集合
			//其中每个SelectionKey代表了一个可以进行IO操作channel
			//一个ServerSocketChannel可以进行IO操作意味着有新的TCP连接加入了
			
			
			Set readyKeys = acceptSelector.selectedKeys();
			Iterator i = readyKeys.iterator();
			
			while(i.hasNext()) {
				SelectionKey sk = (SelectionKey) i.next();
				
				i.remove();
				
				ServerSocketChannel nextReady = (ServerSocketChannel) sk.channel();
				
				Socket s = nextReady.accept().socket();
				
				PrintWriter out = new PrintWriter(s.getOutputStream());
				
				Date now = new Date();
				
				out.println(now);
				
				out.close();
			}
		}
	}

}

后续会追加上更详细的总结和说明!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值