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.
* 一、使用NIO完成网络通信的三个核心
* 1、通道:负责连接
* |--java.nio.channels.channel接口
* |--SelectableChannel
* |--SocketChannel
* |--ServerSocketChannel
* |--DatagramChannel
*
* |--Pipe.SinkChannel
* |--Pipe.SourceChannel
* 2、缓冲区:负责数据的存取
* 3、选择器:是SelectableChannel的多路复用器,用于监控SelectableChannel的IO状况
*
*/
public class TestBlockingNIO {
//客户端
@org.junit.Test
public void client() throws IOException {
// 1、获取通道
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
FileChannel inChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.READ);
//2、分配指定大小的缓冲区
ByteBuffer buffer =ByteBuffer.allocate(1024);
//3、读取本地文件 并发送到服务端
while (inChannel.read(buffer)!=-1){
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
}
//4、关闭通道
socketChannel.close();
inChannel.close();
}
//服务端
@Test
public void server() throws IOException {
//1、获取通道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
FileChannel outChannel = FileChannel.open(Paths.get("3.jpg"),StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//2、绑定连接
serverSocketChannel.bind(new InetSocketAddress(9898));
//3、获取客户端连接
SocketChannel socketChannel = serverSocketChannel.accept();
//4、分配指定大小的缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024); //5、接收客户端的数据,并保存到本地 while (socketChannel.read(buffer)!=-1){
buffer.flip();
outChannel.write(buffer);
buffer.clear();
}
//关闭通道
socketChannel.close();
serverSocketChannel.close(); }
}

最新文章

  1. C#用扩展方法进行自动生成添加删除对象转换的功能
  2. jquery替换所有逗号
  3. 轻量级ORM-Fluentdata入门
  4. python pymysql和orm
  5. 初学python第一天
  6. Technical reading July-15
  7. Python基本数据结构-元组
  8. Away3D 的实体收集器Bug
  9. Greenplum同步到Oracle
  10. mina.net 梳理
  11. 开涛spring3(5.1&5.2) - Spring表达式语言 之 5.1 概述 5.2 SpEL基础
  12. 帆软的报表系统与泛微OA结合起来,这两个软件麦枫提供了经典的服务。
  13. 24点游戏详细截图介绍以及原型、Alpha、Beta对比
  14. 中小型研发团队架构实践六:如何用好消息队列RabbitMQ?
  15. 结合JSFL/actionscript 实现轮廓动画
  16. [PyCharm] 设置自动启动时自动打开项目
  17. Java动态代理的实现方法
  18. 第五章 ReentrantLock源码解析1--获得非公平锁与公平锁lock()
  19. unity, 最简单的additive shader
  20. centos shell基础 alias 变量单引号 双引号 history 错误重定向 2>&1 jobs 环境变量 .bash_history source配置文件 nohup & 后台运行 cut,sort,wc ,uniq ,tee ,tr ,split, paste cat> 2.txt <<EOF 通配符 glob模式 发邮件命令mail 2015-4-8 第十二节课

热门文章

  1. GB2312汉字区位码、交换码和机内码转换方法 (ZT)
  2. 正确配置Linux系统ulimit值的方法
  3. 測试Service
  4. ansible 的user模块
  5. Entity Framework应用:Loading Entities
  6. Tomcat负载均衡和集群环境的搭建
  7. java web中读取properties文件时的路径问题
  8. e575. The Quintessential Drawing Program
  9. Linux远程连接Windows桌面
  10. python cython 模块(2)