📄 httpchatapplet.java
字号:
/**
* @author woexpert@yahoo.com
* @version v0 110100
*/
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class HttpChatApplet extends Applet implements Runnable {
private static final boolean DEBUG = false;
TextArea text;
Label label;
TextField input;
Thread thread;
String user;
public void init() {
// Check if this applet was loaded directly from the filesystem.
// If so, explain to the user that this applet needs to be loaded
// from a server in order to communicate with that server's servlets.
URL codebase = getCodeBase();
if (!"http".equals(codebase.getProtocol())) {
System.out.println();
System.out.println("*** Whoops! ***");
System.out.println("This applet must be loaded from a web server.");
System.out.println("Please try again, this time fetching the HTML");
System.out.println("file containing this servlet as");
System.out.println("\"http://server:port/file.html\".");
System.out.println();
System.exit(1); // Works only from appletviewer
// Browsers throw an exception and muddle on
}
// Get this user's name from an applet parameter set by the servlet
// We could just ask the user, but this demonstrates a
// form of servlet->applet communication.
user = getParameter("user");
if (user == null) user = "anonymous";
// Set up the user interface...
// On top, a large TextArea showing what everyone's saying.
// Underneath, a labeled TextField to accept this user's input.
text = new TextArea();
text.setEditable(false);
label = new Label("Say something: ");
input = new TextField();
input.setEditable(true);
setLayout(new BorderLayout());
Panel panel = new Panel();
panel.setLayout(new BorderLayout());
add("Center", text);
add("South", panel);
panel.add("West", label);
panel.add("Center", input);
}
public void start() {
thread = new Thread(this);
thread.start();
}
String getNextMessage() {
String nextMessage = null;
while (nextMessage == null) {
try {
URL url = new URL(getCodeBase(), "/servlet/ChatServlet");
HttpMessage msg = new HttpMessage(url);
InputStream in = msg.sendGetMessage();
// The following is modified by woexpert to properly convert
// bytes to chars.
// DataInputStream.readLine() is deprecated.
//DataInputStream data = new DataInputStream(
// new BufferedInputStream(in));
BufferedReader data = new BufferedReader(new InputStreamReader(in));
nextMessage = data.readLine();
}
catch (SocketException e) {
// Can't connect to host, report it and wait before trying again
System.out.println("Can't connect to host: " + e.getMessage());
try { Thread.sleep(5000); } catch (InterruptedException ignored) { }
}
catch (FileNotFoundException e) {
// Servlet doesn't exist, report it and wait before trying again
System.out.println("Resource not found: " + e.getMessage());
try { Thread.sleep(5000); } catch (InterruptedException ignored) { }
}
catch (Exception e) {
// Some other problem, report it and wait before trying again
System.out.println("General exception: " +
e.getClass().getName() + ": " + e.getMessage());
try { Thread.sleep(1000); } catch (InterruptedException ignored) { }
}
}
return nextMessage + "\n";
}
public void run() {
while (true) {
//text.appendText(getNextMessage()); // deprecated
text.append(getNextMessage());
}
}
public void stop() {
thread.stop();
thread = null;
}
void broadcastMessage(String message) {
message = user + ": " + message; // Pre-pend the speaker's name
try {
URL url = new URL(getCodeBase(), "/servlet/ChatServlet");
HttpMessage msg = new HttpMessage(url);
Properties props = new Properties();
props.put("message", message);
msg.sendPostMessage(props);
}
catch (SocketException e) {
// Can't connect to host, report it and abandon the broadcast
System.out.println("Can't connect to host: " + e.getMessage());
}
catch (FileNotFoundException e) {
// Servlet doesn't exist, report it and abandon the broadcast
System.out.println("Resource not found: " + e.getMessage());
}
catch (Exception e) {
// Some other problem, report it and abandon the broadcast
System.out.println("General exception: " +
e.getClass().getName() + ": " + e.getMessage());
}
}
public boolean handleEvent(Event event) {
switch (event.id) {
case Event.ACTION_EVENT:
if (event.target == input) {
broadcastMessage(input.getText());
input.setText("");
return true;
}
}
return false;
}
//public void processEvent(AWTEvent awte) {
// if (DEBUG) System.out.println("in HttpChatApplet.processEvnet");
// super.processEvent(awte);
//}
}
class HttpMessage {
URL servlet = null;
Hashtable headers = null;
/**
* Constructs a new HttpMessage that can be used to communicate with the
* servlet at the specified URL.
*
* @param servlet the server resource (typically a servlet) with which
* to communicate
*/
public HttpMessage(URL servlet) {
this.servlet = servlet;
}
/**
* Performs a GET request to the servlet, with no query string.
*
* @return an InputStream to read the response
* @exception IOException if an I/O error occurs
*/
public InputStream sendGetMessage() throws IOException {
return sendGetMessage(null);
}
/**
* Performs a GET request to the servlet, building
* a query string from the supplied properties list.
*
* @param args the properties list from which to build a query string
* @return an InputStream to read the response
* @exception IOException if an I/O error occurs
*/
public InputStream sendGetMessage(Properties args) throws IOException {
String argString = ""; // default
if (args != null) {
argString = "?" + toEncodedString(args);
}
URL url = new URL(servlet.toExternalForm() + argString);
// Turn off caching
URLConnection con = url.openConnection();
con.setUseCaches(false);
// Send headers
sendHeaders(con);
return con.getInputStream();
}
/**
* Performs a POST request to the servlet, building
* post data from the supplied properties list.
*
* @param args the properties list from which to build the post data
* @return an InputStream to read the response
* @exception IOException if an I/O error occurs
*/
public InputStream sendPostMessage(Properties args) throws IOException {
String argString = ""; // default
if (args != null) {
argString = toEncodedString(args); // notice no "?"
}
URLConnection con = servlet.openConnection();
// Prepare for both input and output
con.setDoInput(true);
con.setDoOutput(true);
// Turn off caching
con.setUseCaches(false);
// Work around a Netscape bug
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// Send headers
sendHeaders(con);
// Write the arguments as post data
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(argString);
out.flush();
out.close();
return con.getInputStream();
}
// Send the contents of the headers hashtable to the server
private void sendHeaders(URLConnection con) {
if (headers != null) {
Enumeration enum = headers.keys();
while (enum.hasMoreElements()) {
String name = (String) enum.nextElement();
String value = (String) headers.get(name);
con.setRequestProperty(name, value);
}
}
}
/**
* Converts a properties list to a URL-encoded query string
*/
private String toEncodedString(Properties args) {
StringBuffer buf = new StringBuffer();
Enumeration names = args.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = args.getProperty(name);
buf.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value));
if (names.hasMoreElements()) buf.append("&");
}
return buf.toString();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -