代码:

package bhz.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel; public class Client { //需要一个Selector
public static void main(String[] args) { //创建连接的地址
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8765); //声明连接通道
SocketChannel sc = null; //建立缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024); try {
//打开通道
sc = SocketChannel.open();
//进行连接
sc.connect(address); while(true){
//定义一个字节数组,然后使用系统录入功能:
byte[] bytes = new byte[1024];
System.in.read(bytes); //把数据放到缓冲区中
buf.put(bytes);
//对缓冲区进行复位
buf.flip();
//写出数据
sc.write(buf);
//清空缓冲区数据
buf.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(sc != null){
try {
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} } }
package bhz.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator; public class Server implements Runnable{
//1 多路复用器(管理所有的通道)
private Selector seletor;
//2 建立缓冲区
private ByteBuffer readBuf = ByteBuffer.allocate(1024);
//3
private ByteBuffer writeBuf = ByteBuffer.allocate(1024);
public Server(int port){
try {
//1 打开路复用器
this.seletor = Selector.open();
//2 打开服务器通道
ServerSocketChannel ssc = ServerSocketChannel.open();
//3 设置服务器通道为非阻塞模式
ssc.configureBlocking(false);
//4 绑定地址
ssc.bind(new InetSocketAddress(port));
//5 把服务器通道注册到多路复用器上,并且监听阻塞事件
ssc.register(this.seletor, SelectionKey.OP_ACCEPT); System.out.println("Server start, port :" + port); } catch (IOException e) {
e.printStackTrace();
}
} @Override
public void run() {
while(true){
try {
//1 必须要让多路复用器开始监听
this.seletor.select();
//2 返回多路复用器已经选择的结果集
Iterator<SelectionKey> keys = this.seletor.selectedKeys().iterator();
//3 进行遍历
while(keys.hasNext()){
//4 获取一个选择的元素
SelectionKey key = keys.next();
//5 直接从容器中移除就可以了
keys.remove();
//6 如果是有效的
if(key.isValid()){
//7 如果为阻塞状态
if(key.isAcceptable()){
this.accept(key);
}
//8 如果为可读状态
if(key.isReadable()){
this.read(key);
}
//9 写数据
if(key.isWritable()){
//this.write(key); //ssc
}
} }
} catch (IOException e) {
e.printStackTrace();
}
}
} private void write(SelectionKey key){
//ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
//ssc.register(this.seletor, SelectionKey.OP_WRITE);
} private void read(SelectionKey key) {
try {
//1 清空缓冲区旧的数据
this.readBuf.clear();
//2 获取之前注册的socket通道对象
SocketChannel sc = (SocketChannel) key.channel();
//3 读取数据
int count = sc.read(this.readBuf);
//4 如果没有数据
if(count == -1){
key.channel().close();
key.cancel();
return;
}
//5 有数据则进行读取 读取之前需要进行复位方法(把position 和limit进行复位)
this.readBuf.flip();
//6 根据缓冲区的数据长度创建相应大小的byte数组,接收缓冲区的数据
byte[] bytes = new byte[this.readBuf.remaining()];
//7 接收缓冲区数据
this.readBuf.get(bytes);
//8 打印结果
String body = new String(bytes).trim();
System.out.println("Server : " + body); // 9..可以写回给客户端数据 } catch (IOException e) {
e.printStackTrace();
} } private void accept(SelectionKey key) {
try {
//1 获取服务通道
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
//2 执行阻塞方法
SocketChannel sc = ssc.accept();
//3 设置阻塞模式
sc.configureBlocking(false);
//4 注册到多路复用器上,并设置读取标识
sc.register(this.seletor, SelectionKey.OP_READ);
} catch (IOException e) {
e.printStackTrace();
}
} public static void main(String[] args) { new Thread(new Server(8765)).start();;
} }

最新文章

  1. mybatis使用generator生成对应的model、mapping配置文件、dao
  2. Bootstrap-17
  3. EDIUS中调整YUV曲线的教程
  4. openlayers 注册事件例子
  5. 大作业NABC分析结果
  6. Android Studio开发RecyclerView遇到的各种问题以及解决
  7. 基于 SOA 的组件化业务基础平台
  8. vmtouch - the Virtual Memory Toucher
  9. 公告: 新博客已经迁移到 www.root.run
  10. GCDTimer
  11. 省队集训Day3 tree
  12. 构造AJAX参数, 表单元素JSON相互转换
  13. ubuntu配置android开发环境和编译源码遇到的一些问题
  14. 项目构建之maven篇:2.HelloWorld项目构建过程
  15. Node.js学习 - Global Object
  16. AOP - 2 实例(SpringBoot 注解方式)
  17. Java 异常处理流程
  18. JVM总结-Java 虚拟机是怎么识别目标方法(下)
  19. 发邮件 文字+ 附件的方法(QQ or 网易 邮箱)
  20. web api post/put空值问题以及和angular的冲突的解决

热门文章

  1. 程序设计入门-C语言基础知识-翁恺-第二周:简单的计算程序-详细笔记(二)
  2. Android中的按键顺序打乱
  3. Redis学习总结之三——Redis客户端命令
  4. 微信网页登录Tips
  5. 使用Postman对Restful接口进行测试
  6. Filter学习(二)Filter使用Decorator设计模式
  7. 20179223《Linux内核原理与分析》第十一周学习笔记
  8. webpack wepack-dev-server 对应版本
  9. wordpress分享到微信无缩略图的问题
  10. (转)完美解决 Android WebView 文本框获取焦点后自动放大有关问题