最后的工作
作者Brian Slesinsky
最后要做的是将用户输入的文字传输到闲聊服务器,以使用户可以登录并同其他人聊天。这里是完整的小程序代码。
Chat.java
import java.applet.Applet;
import java.awt.*;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
public class Chat extends Applet implements
Runnable {
TextArea ta;
TextField tf;
Socket s;
Thread t;
OutputStream os;
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);
os = s.getOutputStream();
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<1) avail=1;
if(avail>buf.length) avail=buf.length;
int bytes_read = is.read(buf,0,avail);
int j = 0;
for(int i=0; i<bytes_read; i++) {
if(buf[i]!='\r') {
buf[j++] = buf[i];
}
}
ta.appendText(new String(buf, 0, 0, j));
}
} catch(Exception e) {
System.err.print(e);
}
}
byte[] linebuffer = new byte[80];
public boolean handleEvent(Event e) {
if(e.id==Event.ACTION_EVENT &&
e.target==tf) {
String line = tf.getText();
int len = line.length();
if(len>linebuffer.length-1) len = linebuffer.length-1;
line.getBytes(0, len, linebuffer, 0);
linebuffer[len] = '\n';
try {
os.write(linebuffer, 0, len+1);
} catch(Exception ex) {
System.err.print(ex);
}
tf.setText("");
return true;
}
return false;
}
}