아래의 문서를 번역 및 요약하였습니다.
http://www.cs.brown.edu/courses/cs161/papers/j-nio-ltr.pdf

-----------------------------------------------------------

2. Java I/O의 개념
 
2-1. Java IO와의 차이
 기존 IO는 Stream을 이용한 입출력 이었으나 NIO는 block I/O라는 방식이 사용되었다.

2-2. 왜 NIO가 좋은가?
 NIO는 Native Code의 사용없이도 고성능(속도의 측면이 강함)의 I/O를 사용할 수 있게한다.

2-3. Stream vs Blocks
 Original IO와 NIO의 가장 큰 차이는 '데이터가 어떻게 패키징(package)되고 전송(transmit)되느냐'이다.
 앞서 예기했듯 IO는 Stream을 사용하고 NIO는Block을 사용한다
 
 - Stream 방식
 Original IO input/output시에 데이터의 전송단위는 1byte이다. 물론 Buffer를 사용하지만 buffer를 쓰더라도 궁극적으로 하나의 바이트씩 produce와 consume이 발생한다. 이방식의 성능은 그리 좋지 못하다.
 
 - Block 방식
 block-oriented I/O system의 경우 데이터를 블록의 단위로 다룬다(deal with in blocks). block화된 데이터는 단 한번의 처리단위 시간 동안 일괄 처리된다. 블록으로 데이터를 처리하는것이 stream(byte 기반)으로 처리하는것 보다 훨씬 빠르다. 물론, 빠른만큼 개발자의 구현은 기존 IO보다 힘들어 진다.

주소창에 http://.../list?path=d:\root 와 같이 path를 자신의 local pc의 dir로 지정하면 파일의 리스트를 출력..

사용자 삽입 이미지
해당 파일명의 링크를 클릭하면 파일이 전송됨..
디렉토리는 해당 디렉토리 내부로 이동..



파일 전송을 위한 서블릿 파일
--------------------------------
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.*;
import java.io.*;

/**
 * Servlet implementation class for Servlet: sender
 *
 */
public class sender extends javax.servlet.http.HttpServlet implements
  javax.servlet.Servlet {
 static final long serialVersionUID = 1L;

 /*
  * (non-Java-doc)
  *
  * @see javax.servlet.http.HttpServlet#HttpServlet()
  */
 public sender() {
  super();
 }

 /*
  * (non-Java-doc)
  *
  * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
  *      HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String filePath = request.getParameter("filePath");
  filePath = new String(filePath.getBytes("8859_1"), "euc-kr");
  System.out.println("--->" + filePath);
 
  File file = new File(filePath);
 
  if(file.exists())
  {
   response.setContentType(this.getMimeType(filePath));
   response.setBufferSize(2048);
   response.setContentLength((int)file.length());
   OutputStream os = response.getOutputStream();
   byte[] buf = new byte[2048];
   InputStream is = new FileInputStream(file);
   int n = -1;
   while((n = is.read(buf)) > 0)
   {
    os.write(buf, 0, n);
   }
   is.close();
   os.flush();
   os.close();
  }
  response.encodeRedirectURL("list?path=" + file.getParent());
 }
 
 public String getMimeType(String fileUrl)
   throws java.io.IOException, MalformedURLException {
  String type = null;
  URL u = new File(fileUrl).toURL();
  URLConnection uc = null;
  uc = u.openConnection();
  type = uc.getContentType();
  return type;
 }

 /*
  * (non-Java-doc)
  *
  * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
  *      HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }
}

파일 리스트 출력을 위한 서블릿파일
----------------------------------------------------------
package service.file;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;

/**
 * Servlet implementation class for Servlet: list
 *
 */
public class list extends javax.servlet.http.HttpServlet implements
  javax.servlet.Servlet {
 static final long serialVersionUID = 1L;

 /*
  * (non-Java-doc)
  *
  * @see javax.servlet.http.HttpServlet#HttpServlet()
  */
 public list() {
  super();
 }

 /*
  * (non-Java-doc)
  *
  * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
  *      HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  String rootDir = (String) request.getParameter("path");
  //rootDir = URLDecoder.decode(rootDir, "utf-8");
  rootDir = new String(rootDir.getBytes("8859_1"), "euc-kr");
  response.setContentType("text/html;charset=euc-kr");
  System.out.println(">" + rootDir);
 
  PrintWriter pw = response.getWriter();

  pw.print("<html><head><title>이것은 서블릿</title></head><body>"
    + "이것은 서블릿 페이지다.!!<br><br>FILE:" + rootDir + "<br><br>");
  File dir = new File(rootDir);
  if (dir.exists() && dir.isDirectory())
  {
   pw.print("<br>");
   for (File file : dir.listFiles())
   {
    if (file.isDirectory())
    {
     pw.print("<a href=list?path=" + URLEncoder.encode(file.getCanonicalPath()
       ,"euc-kr")+ ">" + file.getName() + "</a><br>");
    } else if (file.isFile()) {
     pw.print("<a href=sender?filePath=" + URLEncoder.encode(file.getCanonicalPath()
       ,"euc-kr") + ">" + file.getName() + "</a><br>");
    }
   }
  }
  pw.print("</body></html>");
  pw.flush();
  pw.close();
 }


 /*
  * (non-Java-doc)
  *
  * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
  *      HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }
}

'Expired > Java Works' 카테고리의 다른 글

NIO 강좌 - 3  (0) 2008.02.09
NIO 강좌 - 2  (0) 2008.02.09
Java로 EXE 파일 실행..(Excuting exe file by Java Program)  (0) 2007.12.29
실시간 블로그 이미지 갱신..  (0) 2007.12.02
[JMF] JPEG Capture by USB Cam  (0) 2007.11.28

사용자 삽입 이미지

Http(Web) Server에서 Session은 위와같은 구조를 취함(Tomcat4.0 기준)

SessionManaer
1.
Http Header상에 Session(id)값에 의해 해당 객체를 mapping 하는 구조를 취함
   - Session ID값은 Session이 최초생성시 할당됨
2.
Session Manager는 Time(Thread)가 내장되 1분(Default)단위로 Session은 최근 사용시간을 체크,
오랜동안 사용되지 않은 Session을 Hashtable에서 제거함

3.
생성된 session값은 client의 Browser에 저장, 해당 Site에 모든 request protocol에 해당값을 포함시켜 보냄

4.
서버는 request header의 session값으로 해당요청에 대한 처리를 함(ex, 사용자 인증상태 유지)

Session
1.
표준 Interface로 구성

2.
Session ID값, Hashtable 형태의 자료저장소등을 가짐

3. expire method 호출시 valid를 false로 변환되고,
향후 Manager에 의해 Time Scan시 해당 Session이 제거됨(Event에 대한 Notify 부분까지 정의)

4. Session 객체는 서버의 정책에 따라서 Manager에 의해 File이나 DB에 저장될 수 도 있음

아래의 source는 일반적인 실행파일을 자바프로그램이 실행하는 방법입니다.
.NET Framework상에서 구동되는 프로그램은 일부 동작이 되지 않을수도 있습니다.

-------------------------------------------------------------------------------------------
import java.io.*;

public class Test {
 public static void main(String... v) {
  try {
   String cmd = "D:\\Eclipse_wtp\\KoreanLexer\\res\\moHANA\\moHANA.exe";
   Runtime runtime = Runtime.getRuntime();
   Process prc = runtime.exec("res/EXE/kma.exe");
   System.out.println("Input Thread 가동..");
   new InputStreamFromConsole(prc.getInputStream()).start();  // Console 출력을 java IO로 출력
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

// Console 상에 출력되는 message를 출력하기 위한 Thread
class InputStreamFromConsole extends Thread {
 BufferedReader br = null;

 public InputStreamFromConsole(InputStream is) {
   this.br = new BufferedReader(new InputStreamReader(is));
 }

 public void run() {
  String line = "";
  try {
   while ((line = br.readLine()) != null) {
    System.out.println(">" + line);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


[수원 모 오피스텔 실시간 사진]

집에서 놀고 있는 USB 카메라와..
자바 JMF를 이용하여 Webcam for CCTV를 구현하였다.
접속할때 마다 이미지가 갱신된다.
구글맵, 어스와 연동되면 아주 재미있는 서비스가 나올것 같다.

* 현재 AXIS2.0을 이용한 웹서비스 구현중..
* 동영상에 가까운 실시간 갱신도 가능하지만 일단 이건 nio 서버 손좀 봐야 될듯하다..
부하량이 매우크다.. -_-;

자바(Java) JMF를 이용한 USB Cam을 이용한 JPEG 캡쳐

--------------------------------------------------------------------------------------------------
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;

import javax.media.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.media.control.*;
import javax.media.protocol.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;

import com.sun.image.codec.jpeg.*;

public class JPEGCapture {

 public static Player player = null;
 public CaptureDeviceInfo di = null;
 public MediaLocator ml = null;

 public Buffer buf = null;
 public Image img = null;
 public VideoFormat vf = null;
 public BufferToImage btoi = null;

 public JPEGCapture() {
  this.initDevice();
 }

 public void initDevice() {
  String str1 = "vfw:Logitech USB Video Camera:0";
  String str2 = "vfw:Microsoft WDM Image Capture (Win32):0";
  di = CaptureDeviceManager.getDevice(str2);
  ml = di.getLocator();
  try
  {
   player = Manager.createRealizedPlayer(ml);
      player.start();
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }

 public static void playerClose() {
  player.close();
  player.deallocate();
 }

 public void Capture(String absPath) {
  FrameGrabbingControl fgc = (FrameGrabbingControl) player
    .getControl("javax.media.control.FrameGrabbingControl");
  buf = fgc.grabFrame();

  // Convert it to an image
  btoi = new BufferToImage((VideoFormat) buf.getFormat());
  img = btoi.createImage(buf);

  // save image
  saveJPG(img, absPath);
 }

 public static void saveJPG(Image img, String s) {
  BufferedImage bi = new BufferedImage(img.getWidth(null), img
    .getHeight(null), BufferedImage.TYPE_INT_RGB);
  Graphics2D g2 = bi.createGraphics();
  g2.drawImage(img, null, null);

  FileOutputStream out = null;
  try {
   out = new FileOutputStream(s);
  } catch (java.io.FileNotFoundException io) {
   System.out.println("File Not Found");
  }

  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
  param.setQuality(0.5f, false);
  encoder.setJPEGEncodeParam(param);

  try {
   encoder.encode(bi);
   out.close();
  } catch (java.io.IOException io) {
   System.out.println("IOException");
  }
 }
}
---------------------------------------------------------------------------------------------------

JPEGCapture cap = new JPEGCapture();
cap.Capture("C:\\test.jpg");

위와같이 Capture(String) 메소드를 이용하여 캡쳐파일 생성..

+ Recent posts