🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] # 通道Channel java为Channel接口提供的最主要的实现类如下 * FileChannel: 用于读取,写入,映射和操作文件的通道 * SocketChannel: 通过tcp读写网络中的数据 * ServerSocketChannel: 可以监听新进来的tcp连接,对每一个新进来的连接都会创建一个SocketChannel * DatagramChannel: 通过UDP读写网络中的数据通道 # tcp ~~~ //TCP网络编程:使用NIO中的Channel + Buffer 实现客户端给服务器端发送文件,同时,服务器在接收完毕以后,给予反馈 public class BlockingNIOTest1 { @Test public void client() throws Exception{ InetAddress addr = InetAddress.getByName("127.0.0.1"); SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(addr, 9090)); FileChannel fileChannel = FileChannel.open(Paths.get("beauty.jpg"), StandardOpenOption.READ); //使用Channel实现数据的读写 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); while(fileChannel.read(byteBuffer) != -1){ byteBuffer.flip(); socketChannel.write(byteBuffer); byteBuffer.clear(); } //关闭数据的输出 socketChannel.shutdownOutput(); //接收来自于服务器端的数据 socketChannel.read(byteBuffer); byteBuffer.flip(); System.out.println(new String(byteBuffer.array(),0,byteBuffer.limit())); byteBuffer.clear();//可有可无 fileChannel.close(); socketChannel.close(); } @Test public void server() throws Exception{ ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //绑定端口号 serverSocketChannel.bind(new InetSocketAddress(9090)); SocketChannel socketChannel = serverSocketChannel.accept(); //使用FileChannel和SocketChannel实现数据的读写 FileChannel fileChannel = FileChannel.open(Paths.get("beauty4.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); while(socketChannel.read(byteBuffer) != -1){ byteBuffer.flip(); fileChannel.write(byteBuffer); byteBuffer.clear(); } //服务器端在接收完毕数据以后,发送反馈给客户端 byteBuffer.put("人家已收到了你的情意,么么".getBytes()); byteBuffer.flip(); socketChannel.write(byteBuffer); byteBuffer.clear();//可有可无 fileChannel.close(); socketChannel.close(); serverSocketChannel.close(); } } ~~~ # udp ~~~ //针对UDP,使用NIO实现非阻塞式的网络通信 public class NonBlockingNIOTest1 { @Test public void send() throws IOException{ DatagramChannel dc = DatagramChannel.open(); dc.configureBlocking(false); ByteBuffer buf = ByteBuffer.allocate(1024); Scanner scan = new Scanner(System.in); while(scan.hasNext()){ String str = scan.nextLine(); buf.put((new Date().toString() + ":\n" + str).getBytes()); buf.flip(); dc.send(buf, new InetSocketAddress("127.0.0.1", 9898)); buf.clear(); } dc.close(); } @Test public void receive() throws IOException{ DatagramChannel dc = DatagramChannel.open(); dc.configureBlocking(false); dc.bind(new InetSocketAddress(9898)); Selector selector = Selector.open(); dc.register(selector, SelectionKey.OP_READ); while(selector.select() > 0){ Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while(it.hasNext()){ SelectionKey sk = it.next(); if(sk.isReadable()){ ByteBuffer buf = ByteBuffer.allocate(1024); dc.receive(buf); buf.flip(); System.out.println(new String(buf.array(), 0, buf.limit())); buf.clear(); } } it.remove(); } dc.close(); } } ~~~