下面要做的是将文本从闲聊服务器传输到显示屏上作这个工作 最好的办法是应用threadthread随套接口的打开和关闭而打开 和关闭thread能够同时读取相当大量的数据在从套接口读取 数据和更新TextArea方面效率都很高 Chatjava: import javaappletApplet; import javaawt*; import Socket; import javaioInputStream; public class Chat extends Applet implements Runnable { TextArea ta; TextField tf; Socket s; Thread t; public void init() { ta = new TextArea(); tasetEditable(false); add(ta); tf = new TextField(); add(tf); } public void start() { try { String host = getParameter(host); int port = IntegerparseInt(getParameter(port)); s = new Socket(hostport); t = new Thread(this); tstart(); } catch(Exception e) { taappendText(applet error: +e+\n); } } public void stop() { try { tstop(); sclose(); } catch(Exception e) { taappendText(applet error: +e+\n); } } public void run() { try { InputStream is = sgetInputStream(); byte[] buf = new byte[]; while(true) { int avail = isavailable(); if(avail<1) avail=1; if(avail>buflength) avail=buflength; int bytes_read = isread(bufavail); taappendText(new String(buf bytes_read)); } } catch(Exception e) { Systemerrprint(e); } } public boolean handleEvent(Event e) { if(eid==EventACTION_EVENT && etarget==tf) { taappendText(tfgetText()+\n); tfsetText(); return true; } return false; } } |