你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:杂志经典 / 跟高手学编程
用Java实现非阻塞的HTTP服务器(四)
 

 Runtime.getRuntime().availableProcessors() * POOL_MULTIPLE);

    serverSocketChannel= ServerSocketChannel.open();

    serverSocketChannel.socket().setReuseAddress(true);

    serverSocketChannel.socket().bind(new InetSocketAddress(port));

    System.out.println("服务器启动");

  }

  public void service() {

    while (true) {

      SocketChannel socketChannel=null;

      try {

        socketChannel = serverSocketChannel.accept();

        executorService.execute(new Handler(socketChannel));

      }catch (IOException e) {

         e.printStackTrace();

      }

    }

  }

  public static void main(String args[])throws IOException {

    new SimpleHttpServer().service();

  }

  class Handler implements Runnable{   //Handler是内部类,负责处理HTTP请求

  private SocketChannel socketChannel;

  public Handler(SocketChannel socketChannel){

    this.socketChannel=socketChannel;

  }

  public void run(){

    handle(socketChannel);

  }

  public void handle(SocketChannel socketChannel){

    try {

       Socket socket=socketChannel.socket();

       System.out.println("接收到客户连接,来自: " +

      socket.getInetAddress() + ":" +socket.getPort());

 

       ByteBuffer buffer=ByteBuffer.allocate(1024);

       socketChannel.read(buffer);  //接收HTTP请求,假定其长度不超过1024个字节

       buffer.flip();

       String request=decode(buffer);

       System.out.print(request);  //打印HTTP请求

 

       //生成HTTP响应结果

       StringBuffer sb=new StringBuffer("HTTP/1.1 200 OK\r\n");

       sb.append("Content-Type:text/html\r\n\r\n");

       socketChannel.write(encode(sb.toString())); //发送HTTP响应的第一行和响应头

 

         FileInputStream in;

         //获得HTTP请求的第一行

         String firstLineOfRequest=request.substring(0,request.indexOf("\r\n"));

         if(firstLineOfRequest.indexOf("login.htm")!=-1)

            in=new FileInputStream("login.htm");

         else

            in=new FileInputStream("hello.htm");

 

        FileChannel fileChannel=in.getChannel();

        fileChannel.transferTo(0,fileChannel.size(),socketChannel);//发送响应正文

      }catch (Exception e) {

         e.printStackTrace();

      }finally {

         try{

           if(socketChannel!=null)socketChannel.close();  //关闭连结

         }catch (IOException e) {e.printStackTrace();}

      }

  }

  推荐精品文章

·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录
·2023年10月目录
·2023年9月目录 
·2023年8月目录 
·2023年7月目录
·2023年6月目录 
·2023年5月目录
·2023年4月目录 
·2023年3月目录 
·2023年2月目录 
·2023年1月目录 

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089