Introduction
- 애플릿이란
- 보안이 설정된 브라우저 안에서 실행되며, 웹 문서에 내장되는 프로그램이다.
- Java.applet.Applet 클래스를 상속
- 애플릿 기본 메소드 실행 순서
init()
start()
stop()
destroy()
애플릿 적재
- 애플릿 초기화. 처음 시스템에
적재될때 한번만 브라우저에 의해서 자동으로 호출.
애플릿 시작
- Init() 호출 후, 브라우저가
애플릿이 포함되어 잇는 문서를 방문할 때 마다 호출
다른 브라우저로 이동
- 브라우저가 다른 페이저로
이동할 때, destroy()가 호출되기 직전 호출
메모리에서 제거
- 애플릿에 의해 할당된
리소스 환수를 위해 브라우저가 호출
페이지로 되돌아 옴
Introduction
(Cont.)
- 이 장에서는 애플릿과 네트워크 간에 발생하는 상호 작용에 대해 다룬다.
- 애플릿에서
- 관련된 정보 가져오기
- Public URL getDocument()
- public URL getCodeBase()
- 이미지 다운로드하기
- public Image getImage(URL
url)
- public Image getImage(URL
url, String name)
- 사운드 다운로드 하기
- public void play(URL
url)
- public void play(URL
url, String name)
- public AudioClip
getAudioClip(URL url)
- public AudioClip
getAudioClip(URL url, String name)
참고)
OOP에서의
method overload
cf) override
Introduction
(Cont.)
- ImageObserver Interface
- public boolean
imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
- AppletContext 인터페이스의 네트워크 메쏘드들
- public void showDocument(URL
url)
- public void showDocument(URL
url, String target)
- 유용한 프로그램들
- Image Sizer
- 애니메이션 재생기
- 자바로 이미지 맵 구현하기
- 멀티 홈
Introduction
(Cont.)
- MediaTracker 클래스
- 생성자
- public MediaTracker(Component
comp)
- MediaTracker에 이미지 추가하기
- public void addImage(Image
image, int id)
- public void addImage(Image
image, int id, int w, int h)
- 매체의 상태 체크하기
- public boolean checkID(int
id)
- public boolean checkID(int
id, boolean load)
- public boolean checkAll()
- public boolean checkAll(boolean
load)
- 매체가 적재되기를 기다리기
- public void waitForAll() throws InterruptedException
- public boolean waitForAll(long
ms) throws InterruptedException
- public void waitForID(int
id) throws InterruptedException
- public boolean waitForID(int
id, long ms) throws InterruptedException
- public boolean waitForAll(long
ms) throws InterruptedException
- 에러 체크하기
- public boolean isErrorAny()
- public Object[]
getErrorsAny()
- public boolean isErrorID(int
id)
- public Object[]
getErrorsID(int id)
Exception 클래스는
대부분의 프로그램들이 처리해야 하는 예외 상황들을
나타내는 예외 클래스의 부모 클래스이다.
명시적으로
- try … catch 구문 - 예외를 처리해야 한다.
애플릿에서 관련된 정보 가져오기
public class AppletBases extends
Applet {
public void paint(Graphics
g) {
g.drawString("Codebase:
" + getCodeBase().toString(), 10, 40);
g.drawString("Documentbase: " + getDocumentBase().toString(), 10, 65);
}
}
애플릿이 들어있는 디렉토리
애플릿이 내장된 HTML 문서가 들어있는 디렉토리와 문서 이름
애플릿에서 이미지 다운로드하기
public class ImageView extends
Applet {
Image theImage;
public void init()
{
try {
URL u = new URL(getCodeBase(), getParameter("IMAGE"));
theImage = getImage(u);
} catch (MalformedURLException e) {
System.err.println(e); } }
public void paint(Graphics
g) {
g.drawImage(theImage,0,0,this); }}
<APPLET CODE=ImageView WIDTH=500
HEIGHT=500>
<PARAM NAME="IMAGE"
VALUE="titleimage.jpg">
</APPLET>
HTML 소스보기
getImage()의
문제점
- 서버에
이미지가 실제로 존재하는지
확인하기도 전에 제어를 넘긴다.
- 이미지는
프로그램 중의 일부가 실제로 그리기
시작하기 전까지, 또는 강제로 이미지가 적재를
시작하도록 할 때까지 적재되지 않는다.
애플릿에서 사운드 다운로드 하기
- 사운드 파일을 다운로드 한 후 즉시 재생
- public void play(URL
url)
- public void play(URL
url, String name)
public class PlaySound extends Applet {
public void init() {
try {
URL u = new URL(getCodeBase(),
getParameter("SOUND"));
play(u);
} catch (MalformedURLException e) {
System.err.println(e); } } }
ex) PlaySound.html
<APPLET CODE=RelativeGong WIDTH=500 HEIGHT=500>
<PARAM NAME="SOUND" VALUE="spacemusic.au">
</APPLET>
애플릿에서 사운드 다운로드 하기 (Cont.)
- 나중에 재생
- public AudioClip
getAudioClip(URL url)
- public AudioClip
getAudioClip(URL url, String name)
import java.applet.AudioClip;
public class RelativeGong
extends Applet implements Runnable{
AudioClip
theGong;
Thread t;
public void init()
{
try {
URL u = new URL(getCodeBase(),
getParameter("SOUND"));
theGong = getAudioClip(u);
if (theGong != null) {
t = new Thread(this);
t.start();
} } catch (MalformedURLException e) {
System.err.println(e); }}
/* resume() and
suspend () are deprecated
public void start() { t.resume(); }
public void stop() { t.suspend(); }
*/
public void run()
{
Thread.currentThread()
.setPriority(Thread.MIN_PRIORITY);
while(true) {
theGong.play();
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
} } }
}
참고
: Thread
- 프로세스
: 실행중인 프로세스
- 스레드
: 프로세스 내부에서 실행되는 일련의 명령흐름
모든 프로세스는
main 쓰레드
- main()이나 init() - 에서 시작
System.exit()를 호출하지 않는다면
main()이나 init()가 종료될 때
main 쓰레드 종료
스레드를 만든다면,
run()을 시작점과 종료점으로 가짐
Main 스레드를 비롯한 모든 스레드가 종료해야만
종료
프로세스 시작
프로세스 종료
참고
: Thread (Cont.)
Thread 만들기
(1)
class MyFirstThread extends Thread {
public void run()
{
…
}
}
class ThreadTest {
ThreadTest() {
Thread thread = new
MyFirstThread();
thread.start();
…
}
}
Thread 만들기
(2)
class ThreadTest implements Runnable{
ThreadTest() {
Thread thread = new
Thread(this);
thread.start();
…
}
public void run()
{
…
}
}
ImageObserver 인터페이스
- Jvav.awt.image.ImageObserver
- 적재 프로세스를 모니터하여 사용자에게 정보를 제공하고, 이미지가 적재되자 마자 가능한 한 빨리 사용할 수 있도록 해준다.
public class ShowImage extends
Applet {
Image thePicture;
public void init()
{
thePicture = getImage(getCodeBase(), "titleimage.jpg");
}
public void paint(Graphics
g) {
if (!g.drawImage(thePicture,0,0,this))
g.drawString("Loading Picture. Please hang on", 25,50);
}
public boolean
imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
{
if ((infoflags & ImageObserver.ALLBITS) == ImageObserver.ALLBITS)
{
repaint();
return false; // 이미지가 완성되었고,
더 이상의 수정이 필요없으므로 false 반환
}
else return
true; } } // 이미지가
아직도 수정되어야 한다면 true를 반환
public abstract boolean drawImage(Image
img, int x,
int y, ImageObserver observer);
ImageObserver 인터페이스 (Cont.)
- ImageObserver 상수들 ☞ 154p 참조
MediaTracker 클래스
- Java.awt.MediaTracker 클래스
- 여러 장의 이미지 적재 진행 상태를 추적하고, 이것들을
논리적인 그룹으로 묶을 수 있다.
public class trackImage extends
Applet implements Runnable{
Thread thePlay;
Image thePicture;
MediaTracker theTracker;
public void
init() {
// Image 객체 thePicture를 생성하요
이미지를 담을 준비를 한다
thePicture = getImage(getCodeBase(),
"titleimage.jpg");
// MediaTracker 생성자. 보통 인자는
this
theTracker = new MediaTracker(this);
// MediaTracker에 이미지 추가하기.
// 실제 적재는
checkID, checkALL, 또는 세개의 wait() 메쏘드들 중의 하나를
호출해야 한다.
theTracker.addImage(thePicture,1);
thePlay = new Thread(this);
thePlay.start();
}}
MediaTracker 클래스 (Cont.)
public void run()
{
try {
// 1번
ID를 가진 모든 매체가 적재를 시작하도록 강제.
// 완료, 포기,
에러 발생 때까지 blocking
theTracker.waitForID(1);
repaint();
} catch (InterruptedException ie) {}
}
public void paint(Graphics
g) {
// 1번
ID를 가진 모든 이미지가 모두 적재를 마쳤으면 true,
그렇지 않으면 false
if (theTracker.checkID(1,true))
{
g.drawImage(thePicture,0,0,this);
//thePlay.stop();
// deprecated
}
else g.drawString("Loading Picture. Please hand on", 25,50);
}
}
AppletContext 인터페이스의 네트워크 메쏘드들
- 애플릿으로 하여금 자신이 실행되고 있는 환경을 조작할 수 있도록 해 준다
- 애플릿의
getAppletContext() 메쏘드를 호출
public class Redirector extends
Applet{
public void init()
{
AppletContext ac =
getAppletContext();
URL oldURL = getDocumentBase();
try {
URL newURL = new URL(getParameter("NEWHOST") + oldURL.getFile());
// 사용자를
새로운 웹 사이트로 보내주는 이미지 맵 애플릿에서
유용하게 사용
ac.showDocument(newURL);
} catch (MalformedURLException e) {}
}
}
- showDocument()의 목표 프레임 ☞ 167p 참조
AppletContext 인터페이스의 네트워크 메쏘드들
(Cont.)
<APPLET CODE=Redirector
WIDTH=500 HEIGHT=500>
<PARAM NAME="NEWHOST"
VALUE="http://ailab.sogang.ac.kr/">
</APPLET>
HTML 소스보기
URL oldURL = getDocumentBase();
//oldURL = “file:/D:/My Program
Sources/JAVA/index.html”
URL newURL = new URL(getParameter("NEWHOST")
+ oldURL.getFile());
//newURL= “http://ailab.sogang.ac.kr/index.html"
이 경우는 경로를 포함함으로
약간의 수정이 필요?
유용한 프로그램들
- Image Sizer (예제 6-8. ImageSizer.java 참조)
- 사용자로부터 URL을 입력받고, 요청받은 문서를 읽어서, 넓이와 높이 파라미터가 없는 <IMG> 태그 안에 넓이와 높이를
기입하여 HTML을 새로 작성하는 프로그램.
- 넷스케이프의 경우, 각각의 이미지를 보존하기 위해 얼마만큼의 영역이 필요한지에 대한 정보가 확인되면, 그 즉시 텍스트와 부분적인 이미지를 그리기 시작, 적재가 훨씬 빠른 것처럼 보인다.
유용한 프로그램들 (Cont.)
- 애니메이션 재생기 (예제 6-9. Animator.java 참조)
- 연속된 이미지를 보여줌으로써 애니메이션을 만드는 것
public void init() {
...
addMouseListener(new MouseAdapter()
{
public
void mousePressed(MouseEvent me) {
/*
if (running) { play.suspend(); running = false; }
else { play.resume(); running = true; }
*/
Synchronized (Animator.this) {
running = !running;
if (!running)
Animator.this.notify(); } }});
…}
public void run() {
while
(true) {
for (thisCell = 0; thisCell < cells.size(); thisCell++){
try {
theTracker.waitForID(thisCell);
repaint();
play.sleep(90); //delay
Synchronized(this)
{ while (!running) wait(); }
}
catch (InterruptedException ie) {}
}
thisCell
= 0; }}
유용한 프로그램들 (Cont.)
- 자바로 이미지 맵 구현하기
- 전통적인 이미지 맵과는 달리, 자바로 구현된 이미지 맵의 경우에는 최초에 이미지와 위치 정보를 다운로드 받기 위해 서버와 통신할 뿐, 그 이후부터는 서버와 통신할 필요가 없다.
- 예제
6-10. MapArea.java 참조
- 예제
6-11. RectArea.java 참조
- 예제
6-12. ImageMap.java 참조
- 예제
6-13. ImageMapApplet.java 참조
유용한 프로그램들 (Cont.)
- 멀티홈
- 솔라리스의 경우, 하나의 기계가 여러 개의 IP 주소를 갖고서, 각각의 웹 서버를 운영할 수 있도록 한다.
- MacOS의 경우는 지원하지 않다. 이 경우,
http://www.mysite.com/siteA와 http://www.mysite.com/siteB로 지정해야
한다.
- 따라서
http://www.siteA.com과 http://www.siteB.com의 요청을 받으면,
+ oldURL.getFile())을 이용한다. |