NIO 简单http 服务器

来源:互联网 发布:手机txt编辑软件 编辑:程序博客网 时间:2024/06/06 03:44

package normal;

 

import java.io.*;

import java.nio.*;

import java.nio.channels.*;

import java.util.Iterator;

import java.net.*;

 

 

 

@SuppressWarnings("all")

public class NonblockingSingleFileHTTPServer {

 

  private ByteBuffer contentBuffer;

  private int port = 80;

 

  public NonblockingSingleFileHTTPServer(

   ByteBuffer data, String encoding, String MIMEType, int port)

   throws UnsupportedEncodingException {

   

    this.port = port;

    String header = "HTTP/1.0 200 OK/r/n"

     + "Server: OneFile 2.0/r/n"

     + "Content-length: " + data.limit() + "/r/n"

     + "Content-type: " + MIMEType + "/r/n/r/n";

    byte[] headerData = header.getBytes("ASCII");

 

    ByteBuffer buffer = ByteBuffer.allocate(

     data.limit() + headerData.length);

    buffer.put(headerData);

    buffer.put(data);

    buffer.flip();

    this.contentBuffer = buffer;

   

  }

 

  public void run() throws IOException {

 

    ServerSocketChannel serverChannel = ServerSocketChannel.open();

    ServerSocket  serverSocket = serverChannel.socket();

    Selector selector = Selector.open();

    InetSocketAddress localPort = new InetSocketAddress(port);

    serverSocket.bind(localPort);

    serverChannel.configureBlocking(false);

    serverChannel.register(selector, SelectionKey.OP_ACCEPT);

 

    while (true) {

   

      selector.select();

      Iterator keys = selector.selectedKeys().iterator();

      while (keys.hasNext()) {

        SelectionKey key = (SelectionKey) keys.next();

        keys.remove();

        try {

          if (key.isAcceptable()) {

            ServerSocketChannel server = (ServerSocketChannel) key.channel();

            SocketChannel channel = server.accept();

            channel.configureBlocking(false);

            SelectionKey newKey = channel.register(selector, SelectionKey.OP_READ);

          }

          else if (key.isWritable()) {

            SocketChannel channel = (SocketChannel) key.channel();

            ByteBuffer buffer = (ByteBuffer) key.attachment();

            if (buffer.hasRemaining()) {

               channel.write(buffer);  

            }

            else {  // we're done

               channel.close();  

            }

          }

          else if (key.isReadable()) {

            // Don't bother trying to parse the HTTP header.

            // Just read something.

            SocketChannel channel = (SocketChannel) key.channel();

            ByteBuffer buffer = ByteBuffer.allocate(4096);

            channel.read(buffer);

            // switch channel to write-only mode

            key.interestOps(SelectionKey.OP_WRITE);

            key.attach(contentBuffer.duplicate());

          }

        }

        catch (IOException ex) {

          key.cancel();

          try {

            key.channel().close();

          }

          catch (IOException cex) {}

        }

      }

    }

  }

 

  public static void main(String[] args) {

 

    if (args.length == 0) {

      System.out.println(

        "Usage: java NonblockingSingleFileHTTPServer file port encoding");

      return;

    }

     

    try {

      String contentType = "text/plain";

      if (args[0].endsWith(".html") || args[0].endsWith(".htm")) {

        contentType = "text/html";

      }

     

      FileInputStream fin = new FileInputStream(args[0]);

      FileChannel in = fin.getChannel();

      ByteBuffer input = in.map(FileChannel.MapMode.READ_ONLY, 0, in.size());

       

      // set the port to listen on

      int port;

      try {

        port = Integer.parseInt(args[1]);

        if (port < 1 || port > 65535) port = 80;

      } 

      catch (Exception ex) {

        port = 80;

      } 

     

      String encoding = "ASCII";

      if (args.length > 2) encoding = args[2];

      

      NonblockingSingleFileHTTPServer server

       = new NonblockingSingleFileHTTPServer(

         input, encoding, contentType, port);

      server.run();        

 

    }

    catch (Exception ex) {

      ex.printStackTrace();

      System.err.println(ex);

    }

  }

 

}

 

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 7岁宝宝多动症怎么办 小宝宝太调皮了怎么办 3岁宝宝好动怎么办 四岁宝宝好动怎么办 好动的孩子应该怎么办 孩子上课总发呆怎么办 小孩上课发呆走神怎么办 宝宝幼儿园坐不住怎么办 孩孑上课听不懂怎么办 25岁儿子不听话怎么办 幼儿午睡爱说话怎么办 幼儿园实习很累怎么办 怀孕后脚气严重怎么办 拼音a不会写怎么办 儿童7岁还坐不住怎么办 孩子缺锌手蜕皮裂开怎么办 宝宝读幼儿园哭怎么办 幼儿上课爱讲话怎么办 孩子上课总是乱跑怎么办 孩子听不懂老师讲课怎么办 高一上课听不懂怎么办 上课学生纪律差怎么办 一年级学生认字少怎么办 孩子上课做不住怎么办 幼儿园小孩上课乱跑怎么办 孩子挑食不爱吃饭怎么办 幼儿园孩子不听指令怎么办 1岁宝宝多动症怎么办 3岁宝宝胆小怎么办 爱挑食的孩子怎么办 小孩上课经常发呆怎么办 小孩不爱吃饭挑食怎么办 一年级小孩学习不好怎么办 宝宝上课坐不住怎么办 八个月婴儿拉稀怎么办 八个月孕妇拉稀怎么办 孩子好动爱喊怎么办 八个月小孩发烧怎么办 孩子好动怎么办学龄前教育 小孩好动症该怎么办 小孩子好动症该怎么办