Java nioBlocking nio2
Posted 霓裳梦竹
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java nioBlocking nio2相关的知识,希望对你有一定的参考价值。
package com.slp.nio; import org.junit.Test; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; /** * Created by sanglp on 2017/3/1. */ public class TestBlockingNIO2 { //客户端 @org.junit.Test public void client() throws IOException { SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898)); FileChannel fileChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.READ); ByteBuffer buffer = ByteBuffer.allocate(1024); while (fileChannel.read(buffer)!=-1){ buffer.flip(); socketChannel.write(buffer); buffer.clear(); } socketChannel.shutdownOutput();//不加这个会一直处于阻塞状态 //接受服务器反馈 int len=0; while (socketChannel.read(buffer)!=-1){ System.out.println(new String(buffer.array(),0,len)); buffer.clear(); } fileChannel.close(); socketChannel.close(); } //服务端 @Test public void server() throws IOException { ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"),StandardOpenOption.WRITE,StandardOpenOption.CREATE); serverSocketChannel.bind(new InetSocketAddress(9898)); SocketChannel socketChannel = serverSocketChannel.accept(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (socketChannel.read(buffer)!=-1){ buffer.flip(); outChannel.write(buffer); buffer.clear(); } //发送反馈 buffer.put("服务器数据接收成功".getBytes()); buffer.flip(); socketChannel.write(buffer); socketChannel.close(); serverSocketChannel.close(); } }
以上是关于Java nioBlocking nio2的主要内容,如果未能解决你的问题,请参考以下文章
Java NIO2 AsynchronousSocketChannel/AsynchronousServerSocketChannel 和 TLS/SSL