java的nio例子
package main; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
//import java.nio.channels.ClosedChannelException;
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 JsonSocketServer{ private static int PORT = 9090; public static void main(String[] args) {
System.out.println("Server try start ..");
Selector selector = null;
ServerSocketChannel serverSocketChannel = null; try{ selector = Selector.open(); serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().setReuseAddress(true); serverSocketChannel.socket().bind(new InetSocketAddress(PORT) );
//注册可读事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); while (selector.select()>0) {//select()可指定超时参数
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey readyKey = it.next();
it.remove(); handleConnection((ServerSocketChannel) readyKey.channel()); }
}
}catch (IOException e){
System.out.println("IO:"+e.getMessage());
}catch (Exception e){
e.printStackTrace();
}finally{
try{
serverSocketChannel.close();
selector.close();
}catch (Exception e) {
e.printStackTrace();
}
} } private static void handleConnection(ServerSocketChannel serverSocketChannel) throws IOException {
SocketChannel socketChannel = null;
try{
socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
String recvShow = new String(recevceData(socketChannel));
//System.out.println("recv :"+recvShow);
sendData(socketChannel); } catch (IOException e) {
System.out.println("IO"+e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}finally{
socketChannel.close();
}
} private static byte[] recevceData(SocketChannel socketChannel) throws IOException {
int datagramHead = 4;
int recvTimes = 5;
//方法使用的数据类型 ByteBuffer java.nio.channels.SocketChannel.read(ByteBuffer arg0) throws IOException
ByteBuffer buffer = ByteBuffer.allocate(1500);
ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bytes=null;
int len,lenInfo=-1,offset=0;
String s;
try {
while(true){ len = socketChannel.read(buffer);
if(len<0){
System.out.println("read return "+len);
break;
} offset += len; if(len == 0){
if(lenInfo + datagramHead <= offset && lenInfo != -1){
break;
}
else { if(--recvTimes == 0)
break;
Thread.sleep(10);
continue;
}
} buffer.flip();//复位ByteBuffer.position
bytes = new byte[len];
buffer.get(bytes);//把position到limit之间的数据复制到bytes,position会变化
baos.write(bytes);//将本次接收写入缓冲区 if(lenInfo == -1){
s = new String(baos.toByteArray());
lenInfo = Integer.parseInt(s.substring(0,datagramHead));
//System.out.println("len is "+lenInfo);
if(lenInfo + datagramHead <= offset){
break;
}
} buffer.clear();//恢复buffer的初始状态
}
if(len >= 0){
bytes = baos.toByteArray();
}
else {
bytes = new byte[0];
} }catch (IOException e) {
System.out.println("IO"+e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}finally{
baos.close();//关闭缓冲区
} return bytes;
} private static void sendData(SocketChannel socketChannel)throws IOException {
String responseString = "heeeeeee";
//将bytes数组内容写入buffer
ByteBuffer buffer = ByteBuffer.wrap(responseString.getBytes());
try{
socketChannel.write(buffer);
}catch (IOException e) {
System.out.println("IO:"+e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
} }
java的nio例子的更多相关文章
- 漫谈NIO(2)之Java的NIO
1.前言 上章提到过Java的NIO采取的是多路IO复用模式,其衍生出来的模型就是Reactor模型.多路IO复用有两种方式,一种是select/poll,另一种是epoll.在windows系统上使 ...
- java的nio之:java的nio系列教程之buffer的概念
一:java的nio的buffer==>Java NIO中的Buffer用于和NIO通道Channel进行交互.==>数据是从通道channel读入缓冲区buffer,从缓冲区buffer ...
- java的nio之:java的nio系列教程之channel的概念
一:java的nio的channel Java NIO的通道类似流,但又有些不同: ==>既可以从通道中读取数据,又可以写数据到通道.但流的读写通常是单向的. ==>通道可以异步地读写. ...
- java的nio之:java的nio系列教程之概述
一:java的nio的核心组件?Java NIO 由以下几个核心部分组成: ==>Channels ==>Buffers ==>Selectors 虽然Java NIO 中除此之外还 ...
- 输入和输出--java的NIO
Java的NIO 实际开发中NIO使用到的并不多,我并不是说NIO使用情景不多,是说我自己接触的并不是很多,前面我在博客园和CSDN上转载了2篇别人写的文章,这里来大致总结下Java的NIO,大概了解 ...
- 理解Java的NIO
同步与阻塞 同步和异步是针对应用程序和内核的交互而言的. 同步:执行一个操作之后,进程触发IO操作并等待(阻塞)或者轮询的去查看IO的操作(非阻塞)是否完成,等待结果,然后才继续执行后续的操作. 异步 ...
- 一个小时就能理解Java的NIO必须掌握这三大要素!
同步与阻塞 同步和异步是针对应用程序和内核的交互而言的. 同步:执行一个操作之后,进程触发IO操作并等待(阻塞)或者轮询的去查看IO的操作(非阻塞)是否完成,等待结果,然后才继续执行后续的操作. 异步 ...
- Tinking in Java ---Java的NIO和对象序列化
前面一篇博客的IO被称为经典IO,因为他们大多数都是从Java1.0开始就有了的:然后今天这篇博客是关于NIO的,所以的NIO其实就是JDK从1.4开始,Java提供的一系列改进的输入/输出处理的新功 ...
- 少啰嗦!一分钟带你读懂Java的NIO和经典IO的区别
1.引言 很多初涉网络编程的程序员,在研究Java NIO(即异步IO)和经典IO(也就是常说的阻塞式IO)的API时,很快就会发现一个问题:我什么时候应该使用经典IO,什么时候应该使用NIO? 在本 ...
随机推荐
- 跨时代的分布式数据库 – 阿里云DRDS详解(转)
原文章地址:https://www.csdn.net/article/a/2015-08-28/15827676 跨时代的分布式数据库 – 阿里云DRDS详解 发表于2015-08-28 18:39| ...
- sql根据最小值去重
CREATE TABLE temp2 AS SELECT MAX(id) id FROM sys_oper_procenter GROUP BY pro_title 创建一个temp2的表 根据标题分 ...
- Java 管道PipedInputStream PipedOutStream PipedReader PipedWriter
java中的管道流(pipeStream)是一种特殊的流,用于在不同线程间直接传送数据.一个线程发送数据到输出管道,另外一个线程从输入管道中读取数据.通过使用管道,实现不同线程间的通信,而不必借助类似 ...
- 【Nodejs】Expressのファイルアップロード(FileUpload)のMulterについて
https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md Multer 是一个 node.js 中间件,用于处理 mult ...
- ZOJ2018/4月月赛G题Traffic Light(广搜)
题意:首先T组数据,每组数据包括:第一行:一个n,m,然后下面有一个n行m列的01矩阵. 最后一行输入四个数字,分别是起点的横纵坐标,终点的横纵坐标.询问从起点到终点,最少要几步,如果到不了输出-1 ...
- Date 时间 日期 常用方法函数
转载自https://www.cnblogs.com/lcngu/p/5154834.html 一.java.util.Date对象用来表示时间,基本方法如下: Date mDate = new Da ...
- 面向对象中的property装饰器讲解
面向对象中可以用property来修饰我们的函数,必须下面的例子 class Test(object): def __init__(self,name): self.name = name @prop ...
- 小白鼠排队(map容器插入数据的四种方法)
题目描述 N只小白鼠(1 <= N <= 100),每只鼠头上戴着一顶有颜色的帽子.现在称出每只白鼠的重量,要求按照白鼠重量从大到小的顺序输出它们头上帽子的颜色.帽子的颜色用“red”,“ ...
- js实现各种复制到剪贴板的方法
一.实现点击按钮,复制文本框中的的内容 <script type="text/javascript"> function copyUrl2() { var Url2=d ...
- Vue 初始化多个Vue 及之间的相互修改
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...