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();
}
} }

最新文章

  1. 《实战Java虚拟机》,最简单的JVM入门书,京东活动,满200就减100了,该出手了
  2. IO-01. 表格输出(5)
  3. empty()和isset()的区别
  4. FastReport报表
  5. 继电器Relay:ZZR08
  6. 关于Http协议的解析
  7. Topcoder SRM 648 (div.2)
  8. 由世纪互联运营的 Windows Azure 现已在中国正式发布
  9. spark yarn任务的executor 无故 timeout之原因分析
  10. spring容器启动扩展
  11. 01基于配置文件方式的SpringMVC,三种HandlerMapping,三种控制器
  12. Install Air Conditioning HDU - 4756(最小生成树+树形dp)
  13. Python之——CentOS 6.5安装Python2.7.14
  14. 深度学习之Attention Model(注意力模型)
  15. Mysql的学习随笔day1
  16. UVA-10806 Dijkstra, Dijkstra. (最小费用流,网络流建模)
  17. CCNode的属性说明
  18. BloomFilter
  19. SQL Server -&gt;&gt; T-SQL查询面试题之实例版
  20. 无线局域网中RADIUS协议原理与实现

热门文章

  1. 【scrapy】爬虫中报Forbidden by robots.txt
  2. web前端开发浏览器兼容性处理大全
  3. java 1.8
  4. vue 登录前做校验this.$router.push(location)
  5. f5源站获取http/https访问的真实源IP解决方案
  6. Python: PySide(Qt)异步获取网页源码
  7. day 09 函数的进阶
  8. log4j 产生的日志位置设置和catalina.home、catalina.base
  9. MySQL 5.6.4 中TIMESTAMP with implicit DEFAULT value is deprecated 错误
  10. 4N - 素数回文