import java.applet.*; import java.awt.*; import java.net.*; import java.io.*; import java.util.*; public class ChatApplet extends Applet implements Runnable { TextArea text; Label label; TextField input; Thread thread; String user; public void init() { URL codebase = getCodeBase(); user = getParameter("user"); if (user == null) user = "anonymous"; text = new TextArea(); text.setEditable(false); label = new Label("Type here: "); input = new TextField(); input.setEditable(true); setLayout(new BorderLayout()); add("Center", text); Panel panel = new Panel(); panel.setLayout(new BorderLayout()); panel.add("West", label); panel.add("Center", input); add("South", panel); text.appendText("URL: " + codebase + "\n"); } public void start() { thread = new Thread(this); thread.start(); } public void run() { while (true) { text.appendText(contactServer()); } } public boolean handleEvent(Event event) { switch (event.id) { case Event.ACTION_EVENT: if (event.target == input) { broadcastMessage(input.getText() + "\n"); input.setText(""); return true; } } return false; } void broadcastMessage(String message) { message = user + ": " + message; try { URL url = new URL("http://silo.cs.indiana.edu:57960/chat/servlet/ChatServlet"); HttpMessage msg = new HttpMessage(url); Properties props = new Properties(); props.put("message", message); msg.sendPostMessage(props); } catch (Exception ignored) { } } String contactServer() { String nextMessage = null; try { URL servlet = new URL("http://silo.cs.indiana.edu:57960/chat/servlet/ChatServlet"); HttpMessage msg = new HttpMessage(servlet); InputStream in = msg.sendGetMessage(); DataInputStream data = new DataInputStream(new BufferedInputStream(in)); nextMessage = data.readLine(); } catch (Exception e) { try { Thread.sleep(5000); } catch (InterruptedException ignored) { } } return nextMessage + "\n"; } }