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) 收藏 举报 分类: ...
随机推荐
- LeetCode | No.1 两数之和
题目描述: Given an array of integers, return indices of the two numbers such that they add up to a speci ...
- 关于Pytorch中autograd和backward的一些笔记
参考自<Pytorch autograd,backward详解>: 1 Tensor Pytorch中所有的计算其实都可以回归到Tensor上,所以有必要重新认识一下Tensor. 如果我 ...
- python print %s 号格式化输出
python %号格式化输出: 一种字符串格式化的语法, 基本用法是将值插入到%s占位符的字符串中. %s,表示格式化一个对象为字符 "%±(正负号表示)3(数字表示字符串的长度)s&quo ...
- MVC通用仓储类
原文链接:http://www.codeproject.com/Articles/1095323/Generic-Repository-Pattern-MVC 良好的架构师任何项目的核心,开发人员一直 ...
- 配置自己的sublime
我配置的sublime的是这样的,就是在input里输入数据,然后在output里可以得到数据,这样比较方便,看到有的大神还配置背景和其他的,有时间搞一下: 首先把编译器g++配置到环境变量,可以从d ...
- POJ 3970:Party
Party Time Limit: 1000MS Memory Limit: 65536KB 64bit IO Format: %I64d & %I64u Submit Status ...
- Scheduled定时任务器在Springboot中的使用
Scheduled定时任务器是Spring3.0以后自带的一个定时任务器. 使用方式: 1.添加依赖 <!-- 添加 Scheduled 坐标 --> <dependency> ...
- 牛客——Rabbit的字符串
题目: 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32768K,其他语言65536K 64bit IO Format: %lld 题目描述 Rabbit得到了一个字符串,她的好朋 ...
- python进阶(三)~~~装饰器和闭包
一.闭包 满足条件: 1. 函数内嵌套一个函数: 2.外层函数的返回值是内层函数的函数名: 3.内层嵌套函数对外部作用域有一个非全局变量的引用: def func(): print("=== ...
- {转}Java 字符串分割三种方法
http://www.chenwg.com/java/java-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%88%86%E5%89%B2%E4%B8%89%E7%A7%8D%E6%9 ...