下面要做的是将文本从闲聊服务器传输到显示屏上。作这个工作
最好的办法是应用thread。thread随套接口的打开和关闭而打开
和关闭。thread能够同时读取相当大量的数据,在从套接口读取
数据和更新TextArea方面效率都很高。
Chat.java:
import java.applet.Applet;
import java.awt.*;
import java.net.Socket;
import java.io.InputStream;
public class Chat extends Applet implements Runnable {
TextArea ta;
TextField tf;
Socket s;
Thread t;
public void init() {
ta = new TextArea("",20,80);
ta.setEditable(false);
add(ta);
tf = new TextField(80);
add(tf);
}
public void start() {
try {
String host = getParameter("host");
int port = Integer.parseInt(getParameter("port"));
s = new Socket(host,port);
t = new Thread(this);
t.start();
} catch(Exception e) {
ta.appendText("applet error: "+e+"\n");
}
}
public void stop() {
try {
t.stop();
s.close();
} catch(Exception e) {
ta.appendText("applet error: "+e+"\n");
}
}
public void run() {
try {
InputStream is = s.getInputStream();
byte[] buf = new byte[200];
while(true) {
int avail = is.available();
if(avail
if(availbuf.length) avail=buf.length;
int bytes_read = is.read(buf,0,avail);
ta.appendText(new String(buf, 0, 0, bytes_read));
}
} catch(Exception e) {
System.err.print(e);
}
}
public boolean handleEvent(Event e) {
if(e.id==Event.ACTION_EVENT && e.target==tf) {
ta.appendText(tf.getText()+"\n");
tf.setText("");
return true;
}
return false;
}
}