nio 模拟客户端和服务器互相通讯--传输一个int值,并且不断的+1;

服务器,单线程

public class Server {
public static void main(String[] args) {
try {
ServerSocketChannel server=ServerSocketChannel.open().bind(new InetSocketAddress(8881));
server.configureBlocking(false);
Selector selector=Selector.open();
server.register(selector,SelectionKey.OP_ACCEPT);
for(;;) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while(iterator.hasNext()) {
SelectionKey next = iterator.next();
if(next.isAcceptable()) {
acceptHandle(next, selector);
}
if (next.isReadable()) {
doRead(next, selector);
}
iterator.remove();
}
Thread.sleep(2000);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void acceptHandle(SelectionKey key,Selector selector) throws IOException {
ServerSocketChannel serverShannel =(ServerSocketChannel) key.channel();
SocketChannel channel = serverShannel.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ,ByteBuffer.allocate(1024));
}
public static void doRead(SelectionKey key,Selector selector) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer =(ByteBuffer) key.attachment();
buffer.clear();
int read = socketChannel.read(buffer);
int msg=buffer.getInt(0);
System.out.println("服务器收到客户端"+socketChannel.getLocalAddress()+" "+msg);
buffer.rewind();
buffer.putInt(msg+1);
buffer.flip();
socketChannel.write(buffer);
//buffer.clear();
}
}

服务器,多线程

public class Server {
private static ExecutorService executorService = Executors.newFixedThreadPool(4);//指定线程数大小
public static void main(String[] args) {
try {
ServerSocketChannel server=ServerSocketChannel.open().bind(new InetSocketAddress(8881));
server.configureBlocking(false);
Selector selector=Selector.open();
server.register(selector,SelectionKey.OP_ACCEPT);
for(;;) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while(iterator.hasNext()) {
SelectionKey next = iterator.next();
if(next.isAcceptable()) {
acceptHandle(next, selector);
}
if (next.isReadable()) {
executorService.submit(new Runnable() {//调用多线程,,这样子的话就是 accept 一个线程,read,write一个线程
@Override
public void run() {
// TODO Auto-generated method stub
try {
doRead(next, selector);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
iterator.remove();
}
Thread.sleep(2000);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void acceptHandle(SelectionKey key,Selector selector) throws IOException {
ServerSocketChannel serverShannel =(ServerSocketChannel) key.channel();
SocketChannel channel = serverShannel.accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ,ByteBuffer.allocate(1024));
}
public static void doRead(SelectionKey key,Selector selector) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer =(ByteBuffer) key.attachment();
buffer.clear();
int read = socketChannel.read(buffer);
int msg=buffer.getInt(0);
System.out.println(Thread.currentThread().getName()+" 服务器收到客户端"+socketChannel.getLocalAddress()+" "+msg);
buffer.rewind();
buffer.putInt(msg+1);
buffer.flip();
socketChannel.write(buffer);
//buffer.clear();
}
}

客户端

public class Client {
public static void main(String[] args) {
try(SocketChannel channel=SocketChannel.open();
Selector selector=Selector.open();
) {
channel.configureBlocking(false);
if(!channel.connect(new InetSocketAddress("127.0.0.1", 8881))) {
while(!channel.finishConnect()) {};
System.out.println("连接到服务器");
} ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.putInt(1);
buffer.flip();
channel.write(buffer);
channel.register(selector, SelectionKey.OP_READ,buffer);
for(;;) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while(iterator.hasNext()) {
SelectionKey next = iterator.next();
if(next.isReadable()) {
doRead(next,selector);
}
iterator.remove();
}
Thread.sleep(2000);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void doRead(SelectionKey key,Selector selector) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
ByteBuffer buffer =(ByteBuffer) key.attachment();
buffer.clear();
socketChannel.read(buffer);
int msg=buffer.getInt(0);
System.out.println("客户端收到服务器返回的信息"+socketChannel.getLocalAddress()+" "+msg);
buffer.putInt(0,msg+1);
buffer.flip();
socketChannel.write(buffer); } }

**ByteBuffer 是一个缓存区,用来保存用户要传输的数据,里面的读写方法是有一个 position ,limiet ,
capacity。
+ position类似一个指针,可以理解为记事本里的光标。代表了一个位置
+ limit是指针位置的最大限制,
+ capacity指的是容量 就是ByteBuffer的大小。
ByteBuffer 几个方法 clear(), flip(),rewind()等,都是对上面3个值进行操作。
而调用ChannelSocket的read() ,write()方法,传入一个ByteBuffer。都是根据传入的ByteBuffer里的3个值,进行读写。
例如:
```
ByteBuffer buf=new ByteBuffer(1024); //position=0,limit=1024,capacity=1024
buf.putInt(1);//在position为0的位置放入一个int,int为4字节,放完后。position=4;
channel.write(buf);//这里socket去传输这个buffer,这里也是从position=4的地方开始写的,一直写到limit。然后相当于没传数据
```

JAVA nio 简单使用的更多相关文章

  1. Java NIO简单介绍(二)

    上一篇<NIO简单介绍(一)>中讲解了NIO中本地IO相关的内容,这篇重点介绍的NIO的非阻塞式网络通信 一.阻塞与非阻塞 传统的 IO 流都是阻塞式的.也就是说,当一个线程调用 read ...

  2. Java NIO简单介绍(一)

    Java NIO( New IO) 是从Java 1.4版本开始引入的 一个新的IO API,可以替代标准的Java IO API. NIO与原来的IO有同样的作用和目的,但是使用的方式完全不同,NI ...

  3. JAVA NIO 简单介绍

    Version:0.9 StartHTML:-1 EndHTML:-1 StartFragment:00000099 EndFragment:00918492 一:为什么要使用NIO技术        ...

  4. 计算机网络(13)-----java nio手动实现简单的http服务器

    java nio手动实现简单的http服务器  需求分析 最近在学习HTTP协议,还是希望动手去做一做,所以就自己实现了一个http服务器,主要功能是将http请求封装httpRequest,通过解析 ...

  5. 基于 Java NIO 实现简单的 HTTP 服务器

    1.简介 本文是上一篇文章实践篇,在上一篇文章中,我分析了选择器 Selector 的原理.本篇文章,我们来说说 Selector 的应用,如标题所示,这里我基于 Java NIO 实现了一个简单的 ...

  6. 简单即时通讯、聊天室--java NIO版本

    实现的功能: 运行一个服务端,运行多个客户端.在客户端1,发送消息,其余客户端都能收到客户端1发送的消息. 重点: 1.ByteBuffer在使用时,注意flip()方法的调用,否则读取不到消息. 服 ...

  7. Java nio Client端简单示例

    java nio是一种基于Channel.Selector.Buffer的技术,它是一种非阻塞的IO实现方式 以下Client端示例 public class ClientNio { public s ...

  8. 支撑Java NIO 与 NodeJS的底层技术

    支撑Java NIO 与 NodeJS的底层技术 众所周知在近几个版本的Java中增加了一些对Java NIO.NIO2的支持,与此同时NodeJS技术栈中最为人称道的优势之一就是其高性能IO,那么我 ...

  9. JAVA NIO学习笔记1 - 架构简介

    最近项目中遇到不少NIO相关知识,之前对这块接触得较少,算是我的一个盲区,打算花点时间学习,简单做一点个人学习总结. 简介 NIO(New IO)是JDK1.4以后推出的全新IO API,相比传统IO ...

随机推荐

  1. 第八届蓝桥杯java b组第一题

    1,标题: 购物单    小明刚刚找到工作,老板人很好,只是老板夫人很爱购物.老板忙的时候经常让小明帮忙到商场代为购物.小明很厌烦,但又不好推辞.    这不,XX大促销又来了!老板夫人开出了长长的购 ...

  2. 第八届蓝桥杯java b组第二题

    标题:纸牌三角形 A,2,3,4,5,6,7,8,9 共9张纸牌排成一个正三角形(A按1计算).要求每个边的和相等.        下图就是一种排法(如有对齐问题,参看p1.png). A       ...

  3. Mysql 笔记(一)

    InnoDB存储引擎 mysql 存储引擎(好难用,看https://www.zybuluo.com/eqyun/note/27850) 简介 InnoDB是事务安全的MySQL存储引擎,从MySQL ...

  4. Spring框架学习笔记(3)——SpringMVC框架

    SpringMVC框架是基于Spring框架,可以让我们更为方便的进行Web的开发,实现前后端分离 思路和原理 我们之前仿照SpringMVC定义了一个自定义MVC框架,两者的思路其实都是一样的. 建 ...

  5. 讨论c/c++计算小数的精度问题

    求出所有100以下整数与一位小数相乘等于相加的浮点数这个有Bug浮点数计算时精度会出现误差 除非使用非常精确的类型或限制浮点的位数 比如 #include <iostream> int m ...

  6. 一起来学Java注解(Annotation)

    目录 一. 什么是Annotation 二. Annotation的作用 2.1 编译器使用到的注解 2.2 .class文件使用到的注解 2.3 运行期读取的注解 三. 定义Annotation 3 ...

  7. 编写shell脚本实现一键创建KVM虚拟机

    shell脚本一键创建虚拟机 代码如下: #!/bin/bashname=$1 #把位置变量$1重新定义为name(创建虚拟机的名字)path1=/var/lib/libvirt/images/ #i ...

  8. 多线程基础(主要内容转载于https://segmentfault.com/a/1190000014428190)

    进程作为资源分配的基本单位 线程作为资源调度的基本单位,是程序的执行单元,执行路径(单线程:一条执行路径,多线程:多条执行路径).是程序使用CPU的最基本单位. 线程有3个基本状态: 执行.就绪.阻塞 ...

  9. Hbase入门(五)——客户端(Java,Shell,Thrift,Rest,MR,WebUI)

    Hbase的客户端有原生java客户端,Hbase Shell,Thrift,Rest,Mapreduce,WebUI等等. 下面是这几种客户端的常见用法. 一.原生Java客户端 原生java客户端 ...

  10. 强大得分布式项目管理工具Git

    ---恢复内容开始--- 强大的分布式管理工具-Git(一) 前言:最近忙着写项目,在期间呢,用的是git管理,由于一个项目的管理是很重要得,所以整理了一篇关于git得博客跟大家分享一下.大家都知道, ...