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

java select单线程 服务器的更多相关文章

  1. Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解

    Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解 (本文转自: http://blog.csdn.net/yinhaide/article/details/44756 ...

  2. (转载)关于java多线程web服务器 以及相关资料转载

    1.自己实现的简单的java多线程web服务器: https://blog.csdn.net/chongshangyunxiao321/article/details/51095149 自己实现一个简 ...

  3. Java获取Web服务器文件

    Java获取Web服务器文件 如果获取的是服务器上某个目录下的有关文件,就相对比较容易,可以设定死绝对目录,但是如果不能设定死绝对目录,也不确定web服务器的安装目录,可以考虑如下两种方式: 方法一: ...

  4. 一个java页游服务器框架

    一.前言 此游戏服务器架构是一个单服的形式,也就是说所有游戏逻辑在一个工程里,没有区分登陆服务器.战斗服务器.世界服务器等.此架构已成功应用在了多款页游服务器 .在此框架中没有实现相关业务逻辑,只有简 ...

  5. JAVA编写WEB服务器

    一.超文本传输协议  1.1 HTTP请求  1.2 HTTP应答  二.Socket类  三.ServerSocket类  四.Web服务器实例  4.1 HttpServer类  4.2 Requ ...

  6. java socket 单服务器多客户端实时通信

    想用JAVA做一个服务器,请问怎么利用TCP和线程,实现多个客户端同时在线,能与服务器进行交互? 服务器监听端口 做个无限循环 接到一个连接就创建一个通道线程,并将通道线程存储到一个list集合中 1 ...

  7. Java实现http服务器(一)

    基于Java实现Http服务器有多种多样的方法 一种轻量级的方式是使用JDK内置的com.sun.net.httpserver包下和sun.net.httpserver包下类提供的方法构建,该方法轻便 ...

  8. [置顶] java web 动态服务器

    写了一个java web 动态服务器,主要通过内部类来实现,动态类使用了外部类,采用了 classforname 实例化,动态类的构造方法不能带参数, 效果都出来了,分享给有需要的 朋友.判断做的不够 ...

  9. 实战WEB 服务器(JAVA编写WEB服务器)

    实战WEB 服务器(JAVA编写WEB服务器) 标签: web服务服务器javawebsockethttp服务器 2010-04-21 17:09 11631人阅读 评论(24) 收藏 举报  分类: ...

随机推荐

  1. java课程之团队开发冲刺阶段2.8

    昨日总结: 1.具体情况已经写在了昨天的当日总结当中 遇到的问题: 1.toolbar的返回键与菜单键冲突,导致无法同时使用 今天的任务: 1.完整实现课程查询任务 当日总结: 1.完整实现,唯一的遗 ...

  2. Linux / MacOS 下Redis 安装、配置和连接

    下载 下载redis压缩包 最新的为 5.0.4 地址 http://download.redis.io/releases/redis-5.0.4.tar.gz 安装 1 解压 切换工作目录到redi ...

  3. 手机与Arduino蓝牙串口通讯实验及完整例程

    安卓手机与Arduino之间采用蓝牙串口通讯,是很多智能装置和互动装置常用的控制方法,简单而有效,无需网络环境,很实用的技术. 实验采用Arduino UNO板,加了一块1602LCD屏做显示(因为只 ...

  4. 1-3.监督学习(supervised learning)

    定义:监督学习指的就是我们给学习算法一个数据集,这个数据集由“正确答案”组成,然后运用学习算法,算出更多的正确答案.术语叫做回归问题 [监督学习可分为]:回归问题.分类问题.两种 例:一个学生从波特兰 ...

  5. SQL基础教程(第2版)第2章 查询基础:练习题

    SELECT product_name, regist_date FROM Product WHERE regist_date > '2009-04-28'; ① ~ ③中的 SQL 语句都无法 ...

  6. JS基础——脚本位置、数据类型、函数作用域

    (一)脚本位置 JavaScript是嵌套到浏览器里的脚本语言:可放在3个位置: 1.写在头部(head里) <head>    <meta charset="UTF-8& ...

  7. Java学习十四

    学习内容: 1.Junit 2.maven安装配置环境 一.Junit实例演示步骤 1.引入jar包 junit包需要引入hamcrest-core包,否则会报错 2.测试如下代码 package c ...

  8. Thread--使用condition实现顺序执行

    package condition; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Re ...

  9. Feign整合测试

    1.测试使用 (1)服务调用方引入依赖 <dependency> <groupId>org.springframework.cloud</groupId> < ...

  10. linux.linuxidc.com - /2011年资料/Android入门教程/

    本文转自 http://itindex.net/detail/15843-linux.linuxidc.com-%E8%B5%84%E6%96%99-android Shared by Yuan 用户 ...