JAVA高级基础(51)---有反馈的阻塞式的IO网络通信

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();
	}
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值