package org.lanqiao.blocking2.demo;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
/*
* 1. 获取通道
2. 分配指定大小的缓冲区
3. 读取本地文件,并发送到服务端
4. 关闭通道
*/
public class Client {
public static void main(String[] args) throws IOException {
System.out.println("客户端启动....");
//1 获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
//2 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//3 读取本地文件,并发送到服务端
FileChannel fChannel = FileChannel.open(Paths.get("aa.jpg"), StandardOpenOption.READ);
while((fChannel.read(buf)) != -1) {
buf.flip();
sChannel.write(buf);
buf.clear();
}
//告知服务端发送数据完毕
sChannel.shutdownOutput();
//3.1 接收服务端的反馈内容
while(sChannel.read(buf) != -1) {
buf.flip();
byte[] b = buf.array();
System.out.println(new String(b,0,buf.limit()));
}
//4 关闭通道
fChannel.close();
sChannel.close();
}
}
package org.lanqiao.blocking2.demo;
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;
/**服务端:
1. 获取通道
2. 绑定连接
3. 获取客户端连接的通道
4. 分配指定大小的缓冲区
5. 接收客户端的数据,并保存到本地
6. 关闭通道
*/
public class Server {
public static void main(String[] args) throws IOException {
System.out.println("服务端启动...");
//1 获取通道
ServerSocketChannel ssChannel = ServerSocketChannel.open();
//2 绑定链接
ssChannel.bind(new InetSocketAddress( 9898));
// 3 获取客户端的通道
SocketChannel sChannel = ssChannel.accept();
//4分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//5 接收客户端的数据, 并保存到本地
FileChannel fChannel = FileChannel.open(Paths.get("aaCopy.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
while((sChannel.read(buf)) != -1) {
buf.flip();
fChannel.write(buf);
buf.clear();
}
//5.1 向客户端发送反馈内容
buf.put("接收成功".getBytes());
buf.flip();
sChannel.write(buf);
//6 关闭通道
ssChannel.close();
fChannel.close();
sChannel.close();
}
}