【Java】【NIO】【04】通过SocketChannel读写Socket

该Java程序展示了如何使用非阻塞I/O(NIO)的Selector和SocketChannel实现服务器监听客户端连接并接收数据的功能。服务器创建ServerSocketChannel并绑定到5555端口,注册到Selector以监听接受和读取事件。客户端则连接到服务器并发送数据。

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


	package easing.common.java.demo;
	
	import lombok.SneakyThrows;
	
	import java.net.InetSocketAddress;
	import java.nio.ByteBuffer;
	import java.nio.channels.*;
	import java.util.Iterator;
	import java.util.Set;
	
	@SuppressWarnings("all")
	public class Demo {
	
	    public static void main(String[] args) {
	        new Thread(Demo::startServer).start();
	        new Thread(Demo::startClient).start();
	    }
	
	    @SneakyThrows
	    protected static void startServer() {
	
	        //创建ServerSocketChannel
	        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
	        serverSocketChannel.socket().bind(new InetSocketAddress(5555));
	        serverSocketChannel.configureBlocking(false);
	
	        //注册Selector
	        Selector selector = Selector.open();
	        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
	
	        //Selector监听事件
	        while (true) {
	
	            int result = selector.select(2000L);
	
	            Set<SelectionKey> selectedKeys = selector.selectedKeys();
	            Iterator<SelectionKey> iterator = selectedKeys.iterator();
	            while (iterator.hasNext()) {
	                SelectionKey key = iterator.next();
	                //有客户端连接
	                if (key.isAcceptable()) {
	                    SocketChannel socketChannel = serverSocketChannel.accept();
	                    socketChannel.configureBlocking(false);
	                    socketChannel.register(selector, SelectionKey.OP_READ);
	                    System.out.println("Client Connected");
	                }
	                //有客户端可读
	                else if (key.isReadable()) {
	                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
	                    SocketChannel channel = (SocketChannel) key.channel();
	                    while (channel.read(byteBuffer) > 0) {
	                        byteBuffer.flip();
	                        System.out.println("Receive Data from Client: " + new String(byteBuffer.array(), 0, byteBuffer.remaining()));
	                        byteBuffer.clear();
	                    }
	                }
	                //移除已处理过的事件
	                iterator.remove();
	            }
	        }
	    }
	
	    @SneakyThrows
	    protected static void startClient() {
	
	        Thread.currentThread().sleep(2000L);
	
	        //创建ClientSocketChannel
	        SocketChannel socketChannel = SocketChannel.open();
	        socketChannel.configureBlocking(false);
	
	        //连接Server
	        InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", 5555);
	        socketChannel.connect(inetSocketAddress);
	        while (!socketChannel.finishConnect())
	            Thread.currentThread().sleep(100L);
	
	        //向服务端发送数据
	        for (int i = 0; i < 100; i++) {
	            Thread.currentThread().sleep(2000L);
	            ByteBuffer byteBuffer = ByteBuffer.wrap("connect".getBytes());
	            socketChannel.write(byteBuffer);
	        }
	
	        //关闭ClientSocketChannel
	        socketChannel.close();
	    }
	
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值