java select单线程 服务器
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单线程 服务器的更多相关文章
- Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解
Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解 (本文转自: http://blog.csdn.net/yinhaide/article/details/44756 ...
- (转载)关于java多线程web服务器 以及相关资料转载
1.自己实现的简单的java多线程web服务器: https://blog.csdn.net/chongshangyunxiao321/article/details/51095149 自己实现一个简 ...
- Java获取Web服务器文件
Java获取Web服务器文件 如果获取的是服务器上某个目录下的有关文件,就相对比较容易,可以设定死绝对目录,但是如果不能设定死绝对目录,也不确定web服务器的安装目录,可以考虑如下两种方式: 方法一: ...
- 一个java页游服务器框架
一.前言 此游戏服务器架构是一个单服的形式,也就是说所有游戏逻辑在一个工程里,没有区分登陆服务器.战斗服务器.世界服务器等.此架构已成功应用在了多款页游服务器 .在此框架中没有实现相关业务逻辑,只有简 ...
- JAVA编写WEB服务器
一.超文本传输协议 1.1 HTTP请求 1.2 HTTP应答 二.Socket类 三.ServerSocket类 四.Web服务器实例 4.1 HttpServer类 4.2 Requ ...
- java socket 单服务器多客户端实时通信
想用JAVA做一个服务器,请问怎么利用TCP和线程,实现多个客户端同时在线,能与服务器进行交互? 服务器监听端口 做个无限循环 接到一个连接就创建一个通道线程,并将通道线程存储到一个list集合中 1 ...
- Java实现http服务器(一)
基于Java实现Http服务器有多种多样的方法 一种轻量级的方式是使用JDK内置的com.sun.net.httpserver包下和sun.net.httpserver包下类提供的方法构建,该方法轻便 ...
- [置顶] java web 动态服务器
写了一个java web 动态服务器,主要通过内部类来实现,动态类使用了外部类,采用了 classforname 实例化,动态类的构造方法不能带参数, 效果都出来了,分享给有需要的 朋友.判断做的不够 ...
- 实战WEB 服务器(JAVA编写WEB服务器)
实战WEB 服务器(JAVA编写WEB服务器) 标签: web服务服务器javawebsockethttp服务器 2010-04-21 17:09 11631人阅读 评论(24) 收藏 举报 分类: ...
随机推荐
- java: 集合collection
collection是集合层次结构中的根接口,一些集合允许重复元素,而其他集合不允许. 有些collection是有序的,而另一些是无序的. JDK不提供此接口的任何直接实现:它提供了更具体的子接口的 ...
- select * 和select 1 以及 select count(*) 和select count(1)的区别
select 1 和select * select * from 表:查询出表中所有数据,性能比较差: select 常量 from 表:查询出结果是所有记录数的常量,性能比较高: selelct 常 ...
- python函数-函数初识
python函数-函数初识 1.函数的定义 语法 def 函数名(参数1,参数2,参数3,...): '''注释''' 函数体 return 返回的值 2.函数的使用原则---先定义后调用 #定义阶段 ...
- Day 10:浅谈正则表达式
正则表达式 以检验扣扣号是否合法为例引入正则表达式 要求:校验QQ号,要求:必须是5~15位数字,0不能开头. 1.没有正则表达式 public class Demo1 { public static ...
- h5-全屏插件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- java 继承条件下的构造方法调用
运行 TestInherits.java示例,观察输出,注意总结父类与子类之间构造方法的调用关系修改Parent构造方法的代码,显式调用GrandParent的另一个构造函数,注意这句调用代码是否是第 ...
- 使用Map,统计字符串中每个字符出现的次数
package seday13; import java.util.HashMap; import java.util.Map; /** * @author xingsir * 统计字符串中每个字符出 ...
- dac mssql server
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System ...
- JKS not Found
近期使用Spring Boot开发微信验证的时候, 在获取token时,Idea老是提示Jks not found,网上找资料,都说是SSL的问题 实际解决方法: 重装JDK,将JDK重装之后,运行正 ...
- HTML5 之 简单汇总
参考: HTML5的十大新特性 前端面试必备之html5的新特性 HTML5 1.语义化元素 1.1结构元素 标签 描述 article 表示与上下文不相关的独立内容区域 aside 定义页面的侧边栏 ...