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? 在本 ...
随机推荐
- centos搭建OPENldap
LDAP是轻量目录访问协议,英文全称是Lightweight Directory Access Protocol,一般都简称为LDAP.它是基于X.500标准的,但是简单多了并且可以根据需要定制.与X ...
- Js笔记(对象,构造函数,原型,原型链,继承)及一些不熟悉的语法
对象的特性: 1.唯一标识性,即使完全不一样的对象,内存地址也不同,所以他们不相等 2.对象具有状态,同一个对象可能处在不同状态下 3.对象具有行为,即对象的状态可能因为他的行为产生变迁 Js直到es ...
- 解决镜像无法删除的问题multiple repositories
Error response from daemon: conflict: unable to delete ea5f89e79b1e (must be forced) - image is refe ...
- DES算法实现(C++版)
#include "memory.h" #include "stdio.h" enum {encrypt,decrypt};//ENCRYPT:加密,DECRY ...
- linux 重定向命令详解(如1>/dev/null 2>&1)
基础 0:表示标准输入stdin 1:表示标准输出stdout,系统默认为1,可省略(即1>/dev/null等价于>/dev/null) 2:表示标准错误stderr >:表示重定 ...
- Android 基础 (四大组件,五大存储,六大布局)
Android四大组件: 参考:https://blog.csdn.net/shenggaofei/article/details/52450668 Android四大组件分别为activity.se ...
- POJ-3126.PrimePath(欧拉筛素数打表 + BFS)
给出一篇有关素数线性筛和区间筛的博客,有兴趣的读者可以自取. 本题大意: 给定两个四位的素数,没有前导零,每次变换其中的一位,最终使得两个素数相等,输出最小变换次数.要求变换过程中的数也都是素数. 本 ...
- importlib的用法
这个模块可以通过字符串导入模块 比如我们有下面的例子 需要导入的模块的代码 在test_import目录下有一个test1的py文件 name = "中国是个大傻逼" class ...
- swift - 添加定时器
mport UIKit /// 控制定时器的类 class ZDTimerTool: NSObject { /// 定时器 // private var timer: Timer? /// GCD定时 ...
- tomcat-maven-plugin的使用
maven有一个把web应用部署到tomcat下的插件 tomcat-maven-plugin , 我们可以使用这个插件把web应用一键式的部署到一个远程的tomcat中. 插件的url: http: ...