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? 在本 ...
随机推荐
- mysql 多行合并一行
SELECT `w`.`id` AS `id`, `w`.`phone` AS `phone`, `w`.`belong_id` AS `belong_id`, `w`.`name` AS `name ...
- tomcat部署war包
部署步骤 1.下载tomcat 直接在网上下载即可,随便把包下到一个地方 下面文中的xxx均代表tomcat的安装目录 2.将java工程导出war包 在intellij idea的执行左侧选中t ...
- TP3.23 与Laypage 结合进行分页
demo地址:http://tp.ytlwin.top 控制器 <?php namespace Home\Controller; use Think\Controller; class Inde ...
- php71
yum -y install php-mcrypt libmcrypt libmcrypt-devel autoconf freetype gd jpegsrc libmcrypt libpng li ...
- linux下主从同步和redis的用法
前言 mariadb其实就是mysql mysql已经被oracle收购,它即将闭源,马上要开始收费了因此还想免费试用开源的数据库mysql,就在centos7上,将mysql分支为mariadb 操 ...
- PAT1026 (大模拟)
A table tennis club has N tables available to the public. The tables are numbered from 1 to N. For a ...
- android.support.v4与Android.support.v7
Android提供了android.support.v4和android.support.v7两个库,以便低版本API可以使用高版本API的功能. Fragment(碎片)类,是在Android 3. ...
- Mac快捷键大全
Android Studio command+option+L:格式化代码 Visual Studio Code option+shift+f:格式化代码 先按command+k,再按command+ ...
- ES6之扩展运算符
一 将数组转换为用逗号分隔的参数序列 let turtles = ['Leo','Raph','Mikey','Don']; console.log(...turtles); 二 在解构赋值时使用 l ...
- 上海大都会赛 I Matrix Game(最大流)
At the start of the matrix game, we have an N x M matrix. Each grid has some balls.The grid in (i,j) ...