阻塞的IO

@Test
	public void client() throws IOException {
		//获取通道
		SocketChannel sChannel = SocketChannel .open(new InetSocketAddress("127.0.0.1", 8001));
		FileChannel inChannel = FileChannel.open(Paths.get("d:/1.txt"), StandardOpenOption.READ);
		
		
		//分配指定大小的缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		//读取本地文件发送到服务器端
		while ((inChannel.read(buffer))!=-1) {
			buffer.flip();
			sChannel.write(buffer);
			buffer.clear();
		}
		//关闭通道
		inChannel.close();
		sChannel.close();
		
	}
	//服务端
	@Test
	public void server() throws IOException {
		//获取通道
		ServerSocketChannel serverSocket = ServerSocketChannel.open();
		FileChannel outChannel = FileChannel.open(Paths.get("d:/2.txt"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
		//绑定链接
		serverSocket.bind(new InetSocketAddress(8001));
		//获取客户端连接的通道
		SocketChannel socketChannel = serverSocket.accept();
		//分配指定大小的缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		
		//读取客户端的数据并保存到本地
		while ((socketChannel.read(buffer))!=-1) {
			buffer.flip();
			outChannel.write(buffer);
			buffer.clear();
		}
		//关闭对应的通道
		socketChannel.close();
		outChannel.close();
		serverSocket.close();
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值