NIO를 이용한 Super Simple 웹서버 :: 자바네트워크I/O[SSISO Community]
 
SSISO 카페 SSISO Source SSISO 구직 SSISO 쇼핑몰 SSISO 맛집
추천검색어 : JUnit   Log4j   ajax   spring   struts   struts-config.xml   Synchronized   책정보   Ajax 마스터하기   우측부분

자바네트워크I/O
[1]
등록일:2008-05-08 10:08:43 (0%)
작성자:
제목:NIO를 이용한 Super Simple 웹서버
package  mySource;


import  java.net.*;
import  java.nio.*;
import  java.nio.channels.*;
import  java.nio.charset.*;
import  java.util.*;
import  java.io.*;  

public  class  SuperSimpleWebServer
{
  private  Selector  selector  =  null;
  private  ServerSocketChannel  serverSocketChannel  =  null;
  
  private  CharsetDecoder  decoder  =  null;
  private  ByteBuffer  initBuffer  =  null;
  
  public  SuperSimpleWebServer()
  {
    try
    {
      selector  =  Selector.open();
      
      serverSocketChannel  =  ServerSocketChannel.open();
      serverSocketChannel.configureBlocking(false);
      serverSocketChannel.socket().bind(new  InetSocketAddress(80));
      
      serverSocketChannel.register(selector,  SelectionKey.OP_ACCEPT);
      
      decoder  =  Charset.forName("MS949").newDecoder();
      
      this.initServer();
    }
    catch(Exception  e)
    {
      e.printStackTrace();
    }
  }
  
  private  void  initServer()
  {
    try
    {
      initBuffer  =  ByteBuffer.allocateDirect(90);
      initBuffer.put("HTTP/1.1  200  OK\n".getBytes());
      initBuffer.put("Connection:  close\n".getBytes());
      initBuffer.put("Server:  SimpleWebServer\n".getBytes());
      initBuffer.put("Content-Type:  text/html\n".getBytes());
      initBuffer.put("\n".getBytes());
      initBuffer.flip();
    }
    catch(Exception  e)
    {
      e.printStackTrace();
    }
  }
  
  public  void  startWebServer()
  {
    while(true)
    {
      try
      {
        selector.select();
        
        Iterator  iter  =  selector.selectedKeys().iterator();
        
        while(iter.hasNext())
        {
          SelectionKey  key  =  (SelectionKey)iter.next();
          
          if(key.isAcceptable())
          {
            //accept  처리
            this.clientAccept(key);
          }
          else  if(key.isReadable())
          {
            //read  처리
            this.clientRead(key);
          }
          
          iter.remove();
        }
      }
      catch(Exception  e)
      {
        e.printStackTrace();
      }
    }
  }
  
  private  void  clientAccept(SelectionKey  key)
  {
    try
    {
      ServerSocketChannel  ssc  =  (ServerSocketChannel)key.channel();
      SocketChannel  socketChannel  =  ssc.accept();
      socketChannel.configureBlocking(false);
      socketChannel.register(selector,  SelectionKey.OP_READ);
      
      System.out.println(socketChannel.socket().getInetAddress()  +  "  클라이언트가  접속했습니다.");
    }
    catch(Exception  e)
    {
      e.printStackTrace();
    }
  }
  
  private  void  clientRead(SelectionKey  key)
  {
    ByteBuffer  buffer  =  null;
    SocketChannel  sc  =  null;
    String  fileName  =  null;
    StringTokenizer  token  =  null;
    
    try
    {
      buffer  =  ByteBuffer.allocateDirect(1024);
      
      sc  =  (SocketChannel)key.channel();
      sc.read(buffer);
      buffer.flip();
      
      token  =  new  StringTokenizer(decoder.decode(buffer).toString(),  "  ");
      token.nextToken();
      fileName  =  token.nextToken();
      
      buffer.clear();
      buffer  =  null;
      
      if(fileName.equals("/"))
      {
        fileName  =  "index.html";
      }
      else
      {
        fileName  =  fileName.substring(1);
      }
    }
    catch(Exception  e)
    {
      try
      {
        sc.close();
      }
      catch(Exception  ex)
      {
        
      }
    }
    
    this.fileSend(fileName,  sc);
  }
  
  private  void  fileSend(String  fileName,  SocketChannel  sc)
  {
    File  file  =  null;
    MappedByteBuffer  mbuffer  =  null;
    FileChannel  fc  =  null;
    FileInputStream  fis  =  null;
    
    try
    {
      file  =  new  File(fileName);
      fis  =  new  FileInputStream(file);
      fc  =  fis.getChannel();
      
      mbuffer  =  fc.map(FileChannel.MapMode.READ_ONLY,  0L,  fc.size());
      
      sc.write(this.initBuffer);
      sc.write(mbuffer);
      
      this.initBuffer.rewind();
    }
    catch(FileNotFoundException  e)
    {
      //  404  에러
      this.errorMessageSend("404",  sc);
    }
    catch(IOException  ex)
    {
      //  500  에러
      this.errorMessageSend("500",  sc);
    }
    finally
    {
      try
      {
        mbuffer.clear();
        mbuffer  =  null;
        
        fis.close();
        fc.close();
        sc.close();
      }
      catch(Exception  ex)
      {
        
      }
    }
  }
  
  private  void  errorMessageSend(String  msg,  SocketChannel  sc)
  {
    ByteBuffer  buffer  =  null;
    
    try
    {
      System.out.println(sc.socket().getInetAddress()  +  "  클라이언트에게  에러  메시지  전송  :  "  +  msg);
      
      buffer  =  ByteBuffer.allocateDirect(70);
      buffer.put("HTTP/1.0  ".getBytes());
      buffer.put(msg.getBytes());
      buffer.put("  OK\n".getBytes());
      buffer.put("Connection:  close\n".getBytes());
      buffer.put("Server:  SimpleWebServer\n".getBytes());
      buffer.put("\n".getBytes());
      buffer.flip();
      
      sc.write(buffer);
    }
    catch(Exception  e)
    {
      
    }
    finally
    {
      try
      {
        buffer.clear();
        buffer  =  null;
        
        sc.close();
      }
      catch(Exception  ex)
      {
        
      }
    }
  }

  public  static  void  main(String[]  args)
  {
    SuperSimpleWebServer  webServer  =  new  SuperSimpleWebServer();
    webServer.startWebServer();
  }

}
[본문링크] NIO를 이용한 Super Simple 웹서버
[1]
코멘트(이글의 트랙백 주소:/cafe/tb_receive.php?no=7529
작성자
비밀번호

 

SSISOCommunity

[이전]

Copyright byCopyright ⓒ2005, SSISO Community All Rights Reserved.