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例子的更多相关文章

  1. 漫谈NIO(2)之Java的NIO

    1.前言 上章提到过Java的NIO采取的是多路IO复用模式,其衍生出来的模型就是Reactor模型.多路IO复用有两种方式,一种是select/poll,另一种是epoll.在windows系统上使 ...

  2. java的nio之:java的nio系列教程之buffer的概念

    一:java的nio的buffer==>Java NIO中的Buffer用于和NIO通道Channel进行交互.==>数据是从通道channel读入缓冲区buffer,从缓冲区buffer ...

  3. java的nio之:java的nio系列教程之channel的概念

    一:java的nio的channel Java NIO的通道类似流,但又有些不同: ==>既可以从通道中读取数据,又可以写数据到通道.但流的读写通常是单向的. ==>通道可以异步地读写. ...

  4. java的nio之:java的nio系列教程之概述

    一:java的nio的核心组件?Java NIO 由以下几个核心部分组成: ==>Channels ==>Buffers ==>Selectors 虽然Java NIO 中除此之外还 ...

  5. 输入和输出--java的NIO

    Java的NIO 实际开发中NIO使用到的并不多,我并不是说NIO使用情景不多,是说我自己接触的并不是很多,前面我在博客园和CSDN上转载了2篇别人写的文章,这里来大致总结下Java的NIO,大概了解 ...

  6. 理解Java的NIO

    同步与阻塞 同步和异步是针对应用程序和内核的交互而言的. 同步:执行一个操作之后,进程触发IO操作并等待(阻塞)或者轮询的去查看IO的操作(非阻塞)是否完成,等待结果,然后才继续执行后续的操作. 异步 ...

  7. 一个小时就能理解Java的NIO必须掌握这三大要素!

    同步与阻塞 同步和异步是针对应用程序和内核的交互而言的. 同步:执行一个操作之后,进程触发IO操作并等待(阻塞)或者轮询的去查看IO的操作(非阻塞)是否完成,等待结果,然后才继续执行后续的操作. 异步 ...

  8. Tinking in Java ---Java的NIO和对象序列化

    前面一篇博客的IO被称为经典IO,因为他们大多数都是从Java1.0开始就有了的:然后今天这篇博客是关于NIO的,所以的NIO其实就是JDK从1.4开始,Java提供的一系列改进的输入/输出处理的新功 ...

  9. 少啰嗦!一分钟带你读懂Java的NIO和经典IO的区别

    1.引言 很多初涉网络编程的程序员,在研究Java NIO(即异步IO)和经典IO(也就是常说的阻塞式IO)的API时,很快就会发现一个问题:我什么时候应该使用经典IO,什么时候应该使用NIO? 在本 ...

随机推荐

  1. mro具体解释

    你真的理解Python中MRO算法吗? [前言] MRO(Method Resolution Order):方法解析顺序.Python语言包含了很多优秀的特性,其中多重继承就是其中之一,但是多重继承会 ...

  2. c++面向过程和面向对象-C++编译器是如何管理类和对象的

    1,c++编译时如何区分对象调用类的方法? C++中的class从面向对象理论出发,将变量(属性)和函数(方法)集中定义在一起,用于描述现实世界中的类.从计算机的角度,程序依然由数据段(栈区内存)和代 ...

  3. VIM初掌握

    Vim 是 Linux 系统上的最著名的文本/代码编辑器,也是早年的 Vi 编辑器的加强版.它的最大特色是完全使用键盘命令进行编辑,脱离了鼠标操作虽然使得入门变得困难,但上手之后键盘的各种巧妙组合操作 ...

  4. 187. Repeated DNA Sequences (String; Bit)

    All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACG ...

  5. ASP.Net MVC 在ajax接收controller返回值为Json数据

    首先,再次回忆一下ajax的标准用法:(这张图写的比较详细了)(转) 页面部分ajax代码: $.ajax({            url: "/Home/Login?account=&q ...

  6. mysql之 安装(Mac)

    1.官网下载安装包:https://dev.mysql.com/downloads/mysql/ 2.设置环境变量:(1)首先mysql的安装位置为:/usr/local/mysql/bin (2)在 ...

  7. Httpclient 表单,json,multipart/form-data 提交 ---总结常用的方法

    最近在项目中,一直在使用HttpClient 中的方法,这里我进行一些方法的汇总,也是结合了一些大牛写的代码,以备不时之需 官话:HttpClient 是Apache Jakarta Common 下 ...

  8. java_13.2 Object

    1.类 Object 是类层次结构的根类.每个类都使用 Object 作为超类.所有对象(包括数组)都实现这个类的方法 2.hashCode()方法 返回该对象的哈希值.一般情况下,该方法会根据对象的 ...

  9. 通配符的匹配很全面, 但无法找到元素 'tx:annotation-driven' 的声明

    启动Tomcat时报错,通配符的匹配很全面, 但无法找到元素 'tx:annotation-driven' 的声明,报错如下 1.从报错可以看到找不到元素   tx:annotation-driven ...

  10. Django中使用django_debug_toolbar

    一 概述 django_debug_toolbar 是django的第三方工具包,给django扩展了调试功能. 包括查看执行的sql语句,db查询次数,request,headers,调试概览等. ...