package com.nio;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set; public class NIOServer {
public static void main(String[] args) throws IOException, InterruptedException {
Selector selector = Selector.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080);
serverSocketChannel.socket().bind(address);
serverSocketChannel.configureBlocking(false);
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
String content="";
while (true) {
if (selector.select() > 0) {
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> it = selectionKeys.iterator(); while (it.hasNext()) {
SelectionKey selectionKey = it.next();
if (selectionKey.isAcceptable()) {
serverSocketChannel = (ServerSocketChannel)selectionKey.channel();
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
System.out.println("Connected: " + socketChannel.socket().getRemoteSocketAddress());
} else if (selectionKey.isReadable()) {
SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
String msg="";
while (socketChannel.read(buffer) > 0) {
buffer.flip();
byte[] dis = new byte[buffer.limit()];
buffer.get(dis);
content+=new String(dis);
buffer.flip();
msg+=new String(dis);
System.out.println("当前线程="+Thread.currentThread().getId()+"--"+new String(dis));
}
socketChannel.write(ByteBuffer.wrap((new Date()).toString().getBytes()));
socketChannel.close(); }
else if (selectionKey.isWritable()){
// String msg="";
// SocketChannel socketChannel=(SocketChannel)selectionKey.channel();
//
// socketChannel.write(ByteBuffer.wrap(("abc001"+msg).getBytes()));
// socketChannel.close(); } it.remove(); //若不删除,下次执行到selector.select 会持续返回0 造成 死循环
}
} Thread.sleep(100);
}
}
}

使用nio实现web服务器的更多相关文章

  1. reactor模式前序(二):NIO WEB服务器设计

    前文介绍了传统IO的WEB经典服务器 reactor模式前序:传统IO的WEB服务器设计 下面看看JAVA NIO的WEB服务器设计 NIO是基于事件驱动的,对于NIO来说,重要组件是Selector ...

  2. 徒手用Java来写个Web服务器和框架吧<第一章:NIO篇>

    因为有个不会存在大量连接的小的Web服务器需求,不至于用上重量级服务器,于是自己动手写一个服务器. 同时也提供了一个简单的Web框架.能够简单的使用了. 大体的需求包括 能够处理HTTP协议. 能够提 ...

  3. 关于Web服务器的认识

    马上就要毕业了,也要开始找工作了,大学写了这么多代码了,却没有好好总结一下常用的概念很是遗憾额,就通过这篇博客记录一下我最常用的一些知识好了. 说到Web服务器,有很多文章都介绍的很好,之前看到一篇非 ...

  4. 深入理解Tornado——一个异步web服务器

    本人的第一次翻译,转载请注明出处:http://www.cnblogs.com/yiwenshengmei/archive/2011/06/08/understanding_tornado.html原 ...

  5. tomcat解析之简单web服务器(图)

    链接地址:http://gogole.iteye.com/blog/587163 之前有javaeyer推荐了一本书<how tomcat works>,今天晚上看了看,确实不错,第一眼就 ...

  6. 徒手用Java来写个Web服务器和框架吧<第三章:Service的实现和注册>

    徒手用Java来写个Web服务器和框架吧<第一章:NIO篇> 徒手用Java来写个Web服务器和框架吧<第二章:Request和Response> 这一章先把Web框架的功能说 ...

  7. 徒手用Java来写个Web服务器和框架吧<第二章:Request和Response>

    徒手用Java来写个Web服务器和框架吧<第一章:NIO篇> 接上一篇,说到接受了请求,接下来就是解析请求构建Request对象,以及创建Response对象返回. 多有纰漏还请指出.省略 ...

  8. WildFly8(JBoss)默认web服务器-------Undertow

    Java微服务框架之Undertow 一.Undertow简介: Undertow 是红帽公司(RedHat)的开源产品,是 WildFly8(JBoos) 默认的 Web 服务器. 官网API给出一 ...

  9. nginx web服务器详解1(转)

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://freeloda.blog.51cto.com/2033581/1285332 大 ...

随机推荐

  1. LogBack通过MDC实现日志记录区分用户Session

    1.首先实现一个interceptor,在请求开始的时候MDC put一个Session标志,interceptor结束的时候remove掉 public class SessionIntercept ...

  2. Android从无知到有知——NO.2

    这几天虽说偶遇瓶颈.但也渐入佳境.因为之前没有接触过android,所以作为一个新手不会给自己过高的要求.相比于去年做的分布式资源检索,今年的移动开发着实要简单一些.尽管其本质没有太大的差别,但从用户 ...

  3. 实现微信小程序的3rd_session

    function 3rd_session($len) { $fp = @fopen('/dev/urandom','rb'); $result = ''; if ($fp !== FALSE) { $ ...

  4. VMWARE虚拟机安装64位系统此主机支持IntelVTx 但IntelVTx处于禁用状态

    1.进入BIOS(我的电脑是Thinkpad e480,进入按钮是F12/ Fn+F12) 2.选择App Menu,再选择第一项Setup,进入 3.选择Security,选择下面第四项Virtua ...

  5. Sqlite清空表数据

    delete from TableName; //清空数据 where name ='TableName';//自增长ID为0

  6. WinForm 窗口缩放动画效果

    using System; using System.Collections.Generic; using System.Text; using System.Threading; using Sys ...

  7. win7 配置IIS + php 环境

    一:开启win7 的IIS功能:并开启 CGI 二:下载php5 for windows 解压 三:打开IIS --->>处理程序映射- 参考:http://php.net/manual/ ...

  8. cocoaspod使用 引用头文件找不到

    使用cocoasPod做第三方类库管理非常方便,但是在使用的过程之中会遇到一些小问题!比如初次使用会遇到 引入类库,说找不到文件 target--build settings---user searc ...

  9. 算法笔记_032:最长回文串(Java)

    目录 1 问题描述 2 解决方案 2.1 中心扩展法 2.2 Manacher算法   1 问题描述 给定一个字符串,求它的最长回文子串的长度. 2 解决方案 2.1 中心扩展法 此处,首先枚举出回文 ...

  10. Unity3D入门工具介绍(一)

    1.UnitySetup-4.1.2.exe安装包 2unity.pro.4.1.2.patch-MPT.exeUnity3D破解补丁  关于Unity3d 可以看下这个 http://book.2c ...