À̹ø ¾ÆƼŬÀÇ ÁÖÁ¦´Â Applet°ú ServletÀ» ÀÌ¿ëÇÑ Chatting ÀÌ´Ù. Applet¿¡¼´Â Client SocketÀ» ÀÌ¿ëÇÏ°í
Servlet¿¡¼´Â Server SocketÀ» ÀÌ¿ëÇÏ¿© ¼·Î Åë½ÅÀ» ÇÏ°Ô µÈ´Ù.
¢º ServletÀÇ ÀÛµ¿
ÈçÈ÷ chattingÀº Server application°ú Client ApplicationȤÀº AppletÀ¸·Î ¸¸µé¾î Áø´Ù
À̹ø¿¡´Â Server¸¦ ServletÀ¸·Î ±¸Çö ÇÏ°í Client¸¦ AppletÀ¸·Î ȤÀº ApplicationÀ¸·Î Á¢¼ÓÇÏ´Â
ProgramÀ» ¸¸µé¾î º¸µµ·Ï ÇÏÀÚ
Server°¡ ServletÀ¸·Î ¸¸µé¾î Áö¸é ±×¸¸Å Code°¡ ÁÙ¾î µé°í multi Thread·Î µ¿ÀÛÇϴ Ư¼ºÀ» »ì¸°´Ù¸é
»ó´çÈ÷ °£ÆíÇÏ°Ô ±¸Çö ÇϽǼö ÀÖ´Ù. ¶ÇÇÑ ±âÁ¸¿¡ ServletÀ̳ª JSP·Î ¸¸µé¾îÁø Web Site¿¡ ChattingÀ»
ºÙÀ̱â À§Çؼ º°µµÀÇ Server ApplicationÀ» ¸¸µéÁö ¾Ê°íµµ °¡´ÉÇÏ´Ù.
¸ÕÀú ServletÀ» º¸µµ·Ï ÇÏÀÚ.
ChatServlet.java
import java.net.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ChatServlet extends HttpServlet implements Runnable {
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
Thread t = new Thread(this);
t.setDaemon(true);
t.start();
}
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException {
PrintWriter pw=null;
res.setContentType("text/html");
try {
pw = res.getWriter();
} catch(IOException e) { System.err.println("getWriter failed"); }
pw.println("<html>");
pw.println("<head>");
pw.println("<title>Test Chat Applet</title>");
pw.println("</head>");
pw.println("<body>");
pw.println("<applet codebase=\"../../\" code=\"ChatClient.class\" width=450 height=300>");
pw.println("</applet>");
pw.println("</body>");
pw.println("</html>");
pw.close();
}
public void run() {
ServerSocket ss;
try {
ss = new ServerSocket(7777);
} catch(IOException e) {
System.err.println("ServerSocket failed");
return;
}
while(true) {
Socket s = null;
try {
s = ss.accept();
} catch (IOException e) { System.err.println("accept failed"); }
ChatThread ct = new ChatThread(s);
ct.setDaemon(true);
ct.start();
}
}
}
class ChatThread extends Thread {
static Vector v = new Vector();
Socket s;
public ChatThread(Socket s) {
this.s = s;
}
public void run() {
InputStream is=null;
OutputStream os=null;
try {
is = s.getInputStream();
} catch(IOException e) { System.err.println("getInputStream failed"); }
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
os = s.getOutputStream();
} catch(IOException e) { System.err.println("getOutputStream failed"); }
PrintWriter pw = new PrintWriter(os, true);
v.addElement(pw);
while(true) {
String s=null;
try {
s = br.readLine();
if(s == null) {
return;
}
} catch(IOException e) {
System.err.println("readLine failed");
return;
}
for(int i=0; i<v.size(); i++) {
PrintWriter p = (PrintWriter)v.elementAt(i);
p.println(s+"|"+v.size());
if(p.checkError()) {
v.removeElementAt(i);
i--;
}
}
}
}
}
|
|