package com.Select;
/*
*
*select单线程 服务器
*
*/ import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set; public class Myselect {
private Map<SocketChannel, String> map = new HashMap<SocketChannel, String>(); public static void main(String[] args) {
// TODO Auto-generated method stubnew Myselect().initsocket();
} public void initsocket(){
ServerSocketChannel ssc=null;
Selector selector=null;
Iterator<SelectionKey> iter=null;
try {
ssc = ServerSocketChannel.open();
ssc.socket().setReuseAddress(true);
ssc.socket().bind(new InetSocketAddress(8081));
selector = Selector.open();
ssc.configureBlocking(false);
ssc.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
int keys = selector.select(1000);
if (keys <= 0)
continue;
iter=null;
Set<SelectionKey> set_key = selector.selectedKeys();
iter= set_key.iterator();
} catch (Exception e) {
// TODO: handle exception
}
while (iter.hasNext()) {
SelectionKey key = iter.next();
iter.remove();
if (key.isAcceptable()) {
try {
SocketChannel client = ssc.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
} catch (ClosedChannelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (key.isReadable()) {
SocketChannel client = (SocketChannel) key.channel();
ByteBuffer dst = ByteBuffer.allocate(4094);
StringBuffer sb = new StringBuffer();
int readsize = -1;
try {
while ((readsize = client.read(dst)) > 0) {
dst.flip();
sb.append(new String(dst.array(), 0, readsize));
dst.clear();
if (readsize < 0) {//对端关闭,read 返回-1,没有数据返回0,如果客户端一直没有发送数据则isReadable事件激发不了。
System.out.println("client "
+ ((InetSocketAddress) client.getRemoteAddress()).getAddress().getHostAddress()
+ " is closed");
key.cancel();//取消select 监听并关闭服务端socket.
client.close();
continue;
}
map.put(client, sb.toString());//
System.out.println("server read : "+sb.toString());
client.register(selector, SelectionKey.OP_WRITE);
}
} catch (Exception e) {
// TODO: handle exception
} } else if (key.isWritable()) {
System.out.println("coming write\n");
SocketChannel client = (SocketChannel) key.channel();
String req = map.get(client);
if(req==null) {
continue;
}
System.out.println("ready write len"+req.length());
String httpResponse = "HTTP/1.1 200 OK\r\n" +
"Content-Length: "+req.length()+"\r\n" +
"Content-Type: text/html\r\n" +
"\r\n" +req;
// int wcode=client.write(ByteBuffer.wrap(httpResponse.getBytes()));
try {//捕捉异常,客户端端可能关闭导致写异常。
int wcode=client.write(ByteBuffer.wrap(req.getBytes()));
System.out.println("write code "+wcode);
client.register(selector, SelectionKey.OP_READ);
} catch (Exception e) {
// TODO: handle exception
map.remove(client);//关闭服务器端socket,并取消监听
key.cancel();
System.out.println("client is closed!");
try {
client.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
}
}

最新文章

  1. 删除右键ATI CATALYST(R) Control Center的方法
  2. http://blog.csdn.net/liuqinstudy/article/details/8281498
  3. SAP 质检使用非物料基本单位
  4. HDU 1069 Monkey and Banana(动态规划)
  5. 实时动态更新曲线图,x轴时间s随数据的变化而变化
  6. div+css3实现漂亮的多彩标签云,鼠标移动会有动画
  7. Winform DataTable 客户端操作数据
  8. python OptionParser模块
  9. IOS-TextField功能方法详解
  10. redis 安装时候遇到 jemalloc 问题记录
  11. preventDefault()、stopPropagation()、return false 的区别
  12. 201621123002《java程序设计》第十二周学习总结
  13. css基础回顾
  14. Django REST framework 第七章 Schemas &amp; client libraries
  15. nginx基于目录的映射:
  16. Docker 启动 Centos 镜像 提示&quot;Error response from daemon: No command specified&quot;
  17. mysql 多查询临时表的运用
  18. postman优缺点
  19. C# POST请求 json格式
  20. 第6章 征服CSS3选择器(上)

热门文章

  1. storm on yarn(CDH5) 部署笔记
  2. Angular 后台报错记录
  3. 76.Python中F表达式详解
  4. 十七、CI框架之数据库操作insert用法
  5. 禁用 Bootstrap 模态框(Modal) 点击空白时自动关闭
  6. CentOS7使用firewalld的基本命令
  7. 每天一点点之vue框架开发 - axios拦截器的使用
  8. 关于域名转发proxy_pass
  9. Spring原理系列一:Spring Bean的生命周期
  10. import torch 报错