【Java nio】 Blocking nio
2024-10-09 22:32:11
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(); }
}
最新文章
- C#用扩展方法进行自动生成添加删除对象转换的功能
- jquery替换所有逗号
- 轻量级ORM-Fluentdata入门
- python pymysql和orm
- 初学python第一天
- Technical reading July-15
- Python基本数据结构-元组
- Away3D 的实体收集器Bug
- Greenplum同步到Oracle
- mina.net 梳理
- 开涛spring3(5.1&;5.2) - Spring表达式语言 之 5.1 概述 5.2 SpEL基础
- 帆软的报表系统与泛微OA结合起来,这两个软件麦枫提供了经典的服务。
- 24点游戏详细截图介绍以及原型、Alpha、Beta对比
- 中小型研发团队架构实践六:如何用好消息队列RabbitMQ?
- 结合JSFL/actionscript 实现轮廓动画
- [PyCharm] 设置自动启动时自动打开项目
- Java动态代理的实现方法
- 第五章 ReentrantLock源码解析1--获得非公平锁与公平锁lock()
- unity, 最简单的additive shader
- 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 第十二节课