// /* * guestbook.java - 6 Mar 1996 - Version 1.05b (6 Mar 1996) * Copyright 1996 by William Giel, L.S. * E-mail: rvdi@usa.nai.net * WWW: http://www.nai.net/~rvdi/home.htm */ import java.awt.*; import java.applet.*; import java.lang.*; import java.io.*; import java.net.*; import java.util.*; class Send // 메일 발송을 담당하는 클래스 { String result = ""; String lastline; short port = 25; // 메일 포트 DataInputStream in; String mailhost, receiver, sender; public Send( String host,String recvr) { mailhost=host; receiver=recvr; sender=recvr; // 발신자가 수신자와 같음에 유의하자. } void expect(String expected, String msg) throws Exception { // SMTP 서버로부터 expected 값을 기다린다. lastline = in.readLine(); if (!lastline.startsWith(expected)) // expected 스트링이 포함되어 있지 않으면 예외를 throw한다. throw new Exception(msg + ":" + lastline); while (lastline.startsWith(expected + "-")) // expected 스트링에 -가 붙어 있으면 계속해서 다음 줄을 읽어들인다. lastline = in.readLine(); } /* **************** 메일 전송 순서에 대하여 ***************** * * Send 클래스의 mailMessage 도구는 TCP/SMTP 스펙(RFC 821 참고)에 따라 * 25번 포트를 사용하여 메일 서버에 소켓을 연결한다. * 먼저 mailMessage는 '220'을 기다린다. 220은 서비스가 준비되었다는 메시지이다. * 220을 받은 다음에는 지역 호스트의 인터넷 주소 helohost를 구하여 * 소켓을 통하여 "HELO helohost\r\n" 메시지를 전송한다. * 그러면 이 메시지를 받은 SMTP 서버가 '250'을 되돌려준다. * 250은 메일을 보내도 좋다는 승낙(OK)의 의미이다. * 그러면 mailMessage는 "MAIL FROM: sender\r\n" 메시지를 전송하고 * 다시 250이 돌아오면 다시 "RECPT TO: receiver\r\n" 메시지를 전송하고 250을 기다린다. * 이 애플릿에서는 수신자와 발신자가 같음에 유의하자. 생각해 보면 당연하다. * 그 다음에는 "DATA\r\n" 메시지를 전송하고 이번에는 '354'를 기다린다. * DATA 다음에 보낼 것은 "Subject: subject (helohost)" 필드와 하나의 빈 줄("\r\n\r\n")로 * 시작하는 표준 텍스트 메시지이다. RFC 822에 양식이 정의되어 있다. * 빈 줄 다음에는 실제 텍스트가 들어가는데 mailMessage에서는 방문자의 이름(선택적)과 * 방문자의 E-Mail 주소(선택적), 그리고 TextArea에 적은 주석, 접속한 날짜와 * 시간으로 구성된다. * 텍스트 메시지를 전송한 후에 mailMessage는 메시지의 끝을 알리는 마침표("\r\n.\r\n")를 * 전송하고 OK를 뜻하는 250을 기다린다. * 그 다음엔 연결 종료를 뜻하는 "QUIT\r\n" 메시지를 보낸 후 * 서버가 SMTP 채널을 종료함을 뜻하는 221을 기다린다. * 끝으로 mailMessage는 소켓을 닫고 지금까지의 모든 작업이 성공적이었을 경우 true를 되돌린다. * WWW 호스트가 이 SMTP 프로토콜을 지원해야만 자신의 홈페이지에 설치할 때 * 성공적으로 실행될 것이다. * 그렇지 않으면 이 애플릿의 환경을 직접 바꿔야 한다. */ public boolean mailMessage(String subject,String message) // 실제 메일을 발송 { if (null==receiver) return false; // 수신자가 없으면 메일을 발송하지 않는다. Socket s = null; try { String res; s = new Socket(mailhost, port); // 클라이언트 소켓을 생성하여 호스트의 메일 포트에 연결한다. PrintStream p = new PrintStream(s.getOutputStream()); in = new DataInputStream(s.getInputStream()); // 연결된 소켓으로부터 입력 스트림과 출력 스트림을 구한다. expect("220", "no greeting"); String helohost = InetAddress.getLocalHost().toString(); // 로컬 호스트의 인터넷 주소를 구한다. p.print("HELO " + helohost + "\r\n"); // SMTP 서버로 메시지 전송 expect("250", "helo"); int pos; String hello = "Hello "; if ((pos = lastline.indexOf(hello)) != -1) { // 서버로부터 받은 메시지에 "Hello "가 있으면 helohost = lastline.substring(pos + hello.length()); // "Hello " 바로 다음의 스트링을 helohost로 한다. helohost = helohost.substring(0, helohost.indexOf(' ')); // 다시 helohost 스트링에 포함된 첫 공백 문자부터를 helohost로 한다. } p.print("MAIL FROM: " + sender + "\r\n"); expect("250", "mail from"); p.print("RCPT TO: " + receiver + "\r\n"); expect("250", "rcpt to"); p.print("DATA\r\n"); expect("354", "data"); p.print("Subject: " + subject); p.print(" (" + helohost + ")"); p.print("\r\n\r\n"); DataInputStream is = new DataInputStream(new StringBufferInputStream(message)); // 스트링인 message를 데이터입력스트림으로 변환 while (is.available() > 0) { String ln = is.readLine(); if (ln.equals(".")) // 마침표 하나는 메시지의 끝을 뜻하므로 변환 ln = ".."; p.println(ln); } String days="SunMonTueWedThuFriSat"; String months="JanFebMarAprMayJunJulAugSepOctNovDec"; Date date=new Date(); // 현재 날짜와 시간을 구한다. p.print("(Accessed at " + Integer.toString(date.getHours()) + ":" + Integer.toString(date.getMinutes()) + " on " + days.substring(date.getDay()*3,date.getDay()*3+3) + ", " + Integer.toString(date.getDate()) + " " + months.substring(date.getMonth()*3,date.getMonth()*3+3) + " " + Integer.toString(date.getYear()+1900) + ")"); p.print("\r\n.\r\n"); expect("250", "end of data"); p.print("QUIT\r\n"); expect("221", "quit"); } catch(Exception e) { result = e.getMessage(); return false; } finally { // finally는 예외 발생 유무에 관계 없이 실행하는 블록을 지정하는 예약어 try { if (s != null)s.close(); } catch(Exception e) { result = e.getMessage(); } return true; } // end of finally } } class guestbookWindow extends Frame // guestbook 애플릿이 생성하는 대화상자 윈도우 { static final int FONTHEIGHT=12; // 글꼴 크기 static final String FONTSTRING="System"; // 글꼴 TextArea txt3=null; // 메일에 들어갈 내용을 쓰는 TextArea TextField txt1=null; // 발신자의 이름을 쓰는 TextField TextField txt2=null; // 발신자의 E-Mail 주소를 쓰는 TextField Send send=null; // 전자 우편을 보내는 클래스 인스턴스 AppletContext appletContext; // AppletContext는 애플릿의 환경인 웹 브라우저나 애플릿뷰어에 // 관련된 정보를 얻을 때 사용하는 추상 클래스(인터페이스)이다. public guestbookWindow(AppletContext app, String mailhost,String receiver) // 생성자 { send= new Send(mailhost,receiver); // 전자 우편 발송을 하는 Send 클래스 인스턴스 생성 appletContext=app; // guestbook 애플릿의 AppletContext를 저장 Label lbl1,lbl2,lbl3; // 세 개의 안내 레이블 Button butt1, butt2; // Send, Cancel 두 개의 버튼 GridBagLayout gridbag=new GridBagLayout(); // 레이아웃 관리자로 GridBagLayout 사용 GridBagConstraints c=new GridBagConstraints(); // GridBagLayout의 세부 항목을 지정하는 GridBagConstraints 클래스 인스턴스 생성 setFont(new Font(FONTSTRING,Font.BOLD,FONTHEIGHT)); // 현재 글꼴을 시스템, 볼드, 12포인트로 setLayout(gridbag); // 레이아웃 관리자 지정 setBackground(Color.lightGray); // 윈도우의 배경색을 연한 회색으로 c.fill=GridBagConstraints.NONE; // 디스플레이 영역보다 성분 윈도우가 작더라도 늘리지 않음. c.weightx=1.0;c.weighty=1.0; // 여백 분배 시 가중치 지정 c.ipadx=4;c.ipady=4; // 내부 여백 값 지정 c.insets=new Insets(5,5,5,5); // 외부 여백 값 지정 lbl1 = new Label("Your Name (Optional):"); // 레이블 생성 gridbag.setConstraints(lbl1,c); // 생성된 레이블의 위치 지정 add(lbl1); // 레이블을 실제로 대화상자에 추가 c.anchor=GridBagConstraints.WEST; // 디스플레이 영역보다 작을 경우 서쪽으로 붙여 배열 txt1 = new TextField("", 20); // 가시영역 크기가 20 칸인 TextField 생성 gridbag.setConstraints(txt1,c); add(txt1); c.anchor=GridBagConstraints.CENTER; // 디스플레이 영역보다 작을 경우 가운데에 배열 butt1 = new Button("Send"); // Send 버튼 생성 gridbag.setConstraints(butt1,c); add(butt1); c.gridwidth=GridBagConstraints.REMAINDER; // 가로 방향의 마지막 성분 윈도우로 지정 butt2 = new Button("Cancel"); // Cancel 버튼 생성 gridbag.setConstraints(butt2,c); add(butt2); c.gridwidth=1; // 다시 기본값으로 c.weightx=1.0;c.weighty=1.0; lbl2 = new Label("Your EMail(Optional):"); // 레이블 생성 gridbag.setConstraints(lbl2,c); add(lbl2); c.gridwidth=GridBagConstraints.REMAINDER; // 가로 방향의 마지막 성분 윈도우로 지정 c.anchor=GridBagConstraints.WEST; // 디스플레이 영역의 서쪽에 배열 txt2 = new TextField("", 20); // TextField 생성 gridbag.setConstraints(txt2,c); add(txt2); c.gridwidth=GridBagConstraints.REMAINDER; // 성분 윈도우 하나가 가로를 모두 차지 c.fill=GridBagConstraints.BOTH; // 디스플레이 영역을 성분 윈도우가 완전히 채우도록 늘인다. lbl3=new Label("Any comments or suggestions?"); gridbag.setConstraints(lbl3,c); add(lbl3); c.gridwidth=GridBagConstraints.REMAINDER; // 성분 윈도우 하나가 가로를 모두 차지 c.fill=GridBagConstraints.BOTH; // 디스플레이 영역을 완전히 채움 txt3 = new TextArea(5,66); // 세로 5줄, 가로 66칸짜리 TextArea 생성 gridbag.setConstraints(txt3,c); add(txt3); } // 생성자에서는 pack(), show() 도구를 호출하지 않음에 유의 public boolean action(Event evt, Object arg) // 버튼이 눌려진 경우 { if(arg.equals("Cancel")) { // Cancel 버튼이 눌려진 경우 hide(); // 대화상자 윈도우를 보이지 않게 한다. return true; } else if (arg.equals("Send")) { // Send 버튼이 눌려진 경우 hide(); // 대화상자 윈도우를 보이지 않게 한다. if (txt1.getText().length()>0 || // 입력된 텍스트들을 하나의 스트링으로 txt2.getText().length()>0 || // Send 클래스의 mailMessage를 호출하여 txt3.getText().length()>0) { // 메일을 발송한다. String message="Guest: " + txt1.getText() + "\n" + "Address: " + txt2.getText() + "\n\n" + txt3.getText() ; if (true==send.mailMessage("Guestbook Entry!",message)) // 메일 발송 성공 appletContext.showStatus("Entry logged into guest book!"); // 브라우저의 상태 바에 지정한 텍스트를 출력한다. else // 메일 발송 실패 appletContext.showStatus("Entry NOT logged."); } else // TextField와 TextArea에 입력이 하나도 없을 경우 appletContext.showStatus("Nothing to send!"); // 브라우저의 상태 바에 에러 메시지 출력 return true; } return false; } public synchronized boolean handleEvent(Event e) { // 아이콘화 단추나 종료 단추가 눌러질 경우 대화 상자를 감춘다. if (e.id == Event.WINDOW_ICONIFY || e.id == Event.WINDOW_DESTROY) { hide(); return true; } return super.handleEvent(e); // 이벤트를 처리하지 않을 경우 부모 클래스의 도구를 호출 } public void show() // 화면에 대화상자를 나타낼 때에는 각 텍스트를 없앤다. { txt1.setText(""); txt2.setText(""); txt3.setText(""); super.show(); // 화면에 대화상자 윈도우를 표시 } } public class guestbook extends Applet // guestbook 애플릿 클래스 { static final int FONTHEIGHT=12; // 12 포인트 (글꼴 크기) static final String FONTSTRING="System"; // 시스템 글꼴 static final String BUTTON = "Guest Book"; // 버튼 레이블 static final String VERSION = "GUESTBOOK.JAVA - v1.05b - 6 March 1996"; static final String COPYRIGHT= "(C)1996 by W.Giel"; guestbookWindow window=null; // 버튼을 누르면 생성되는 대화상자 윈도우 인스턴스 Image image=null; // 버튼 아래에 배치되는 그림, 초기에는 null Button button; int width, height; MediaTracker tracker = new MediaTracker(this); // 이 애플릿의 MediaTracker 생성 public String[][] getParameterInfo() // 애플릿이 사용하는 태그들을 안내해주는 { // Applet 클래스의 도구를 오버라이드한다. String[][] info = { // "변수 이름", "유형", "설명"의 순서이다. {"width", "int", "width of the applet, in pixels"}, {"height", "int", "height of the applet, in pixels"}, {"receiver", "string", "SMTP 'RCPT TO:' parameter "}, {"imageurl", "string", "name of icon to display "}, {"title", "string", "title for popup dialog "}, }; return info; } // 애플릿의 저자, 버전, 저작권에 대한 안내를 하는 Applet 클래스의 도구를 오버라이드. public String getAppletInfo() { return ( VERSION + " - simulates a guest log\n" + "by E-mailing guest data to page owner, by Bill Giel\n" + "http://www.nai.net/~rvdi/home.htm or rvdi@usa.nai.net\n" + "Copyright 1996 by William Giel."); } public void init() // 애플릿이 실행되면 브라우저에 의해 호출 { String receiver, szImage, szTitle; URL imageURL=null; receiver = getParameter("receiver"); // 메일을 보낼 주소를 얻는다. if(null == receiver) showStatus("No RECEIVER parameter - applet will not log entry!"); // HTML 문서에 receiver 변수가 없으면 브라우저 상태바에 에러 출력 if (null==(szTitle=getParameter("title"))) // HTML 문서에 title 변수가 없을 경우 szTitle="Guest Book"; szImage=getParameter("IMAGEURL"); // 애플릿의 버튼 아래에 나타낼 이미지를 얻는다. window=new guestbookWindow(getAppletContext(),getCodeBase().getHost(),receiver); // 대화상자를 생성. pack(), show()를 호출하지 않았으므로 화면에 나타나지는 않는다. window.setTitle(szTitle); // 입력 받은 title 변수로 대화상자 타이틀을 지정 window.pack(); // 대화상자의 레이아웃을 실제로 수행 setFont(new Font(FONTSTRING,Font.BOLD,FONTHEIGHT)); // 글꼴을 시스템, 볼드, 12포인트로 지정 add (button = new Button(BUTTON)); // BUTTON("Guest Book"으로 지정) 레이블을 가진 버튼 생성해서 애플릿에 추가 width=size().width; height=size().height; // 현재 폭과 높이를 유지 if (null != szImage) { // 이미지가 지정되어 있으면 URL으로 바꾼다. try{ imageURL=new URL(getDocumentBase(),szImage); } catch (MalformedURLException e) { imageURL=null; image=null; } } if (imageURL != null) { // URL을 이용하여 지정된 이미지를 얻는다. image=getImage(imageURL); if (image != null) tracker.addImage(image,0); // 애플릿의 MediaTracker에 추가 } button.move( (width-button.size().width)/2, (width-button.size().width)/2 ); // 버튼의 위치를 재지정 } // init() 끝 public void paint(Graphics g) { Color color=g.getColor(); // 현재의 색을 저장한다. g.setColor(Color.lightGray); // 연한 회색으로 현재 색을 변경한다. g.fill3DRect(0,0,size().width,size().height,true); // 현재 색을 사용하여 3차원 사각형을 그린다. // 마지막의 true 인자는 사각형이 튀어나옴을 지정한다. g.setColor(color); // 현재 색을 원래 색으로 되돌린다. if (image != null){ try { tracker.waitForID(0); // MediaTracker로 이미지를 읽어들인다. /* waitForID()는 지정된 ID를 가진 모든 이미지들을 읽어들이기 시작해서 모두 읽어들였거나 에러를 받으면 중단 한다. 에러가 있을 경우 statusID() 또는 isErrorID()를 사용하여 검사해볼 수 있다. */ } catch (InterruptedException e) { return; } g.drawImage(image,(width-image.getWidth(this))/2,button.size().height +(height-image.getHeight(this)-button.size().height)/3,this); // 읽어들인 이미지를 버튼 아래에 그린다. g.setFont(new Font(FONTSTRING,Font.PLAIN,12)); // 글꼴을 시스템, 보통체, 12포인트로 지정 FontMetrics fm=g.getFontMetrics(); // 글꼴 정보를 얻는다. g.drawString(COPYRIGHT, (width-fm.stringWidth(COPYRIGHT))/2, height-fm.getMaxDescent()-3); // 저작권 스트링을 애플릿 아래 부분에 쓴다. } } // paint() 끝 public boolean action(Event evt, Object arg) { if(arg.equals(BUTTON) && !window.isShowing()) { // "Guest Book" 버튼이 눌려지고 대화상자를 아직 화면에 나타내지 않았다면 window.show(); // 대화상자를 화면에 나타낸다. return true; } else return false; } }