连接到闲聊服务器上
作者Brian Slesinsky
现在我们已经有了一个用户界面,我们需要将其连接到闲聊服务
器上。我们需要有一个套接口,要打开连接,我们需要知道闲聊
服务器名称和断口的号码。最好使用小程序的参数,这样在改变
参数时无需重新编译该小程序。
如果一个用户离开乐闲聊室,我们需要让闲聊室内的其他人知道
该情况,所以用户离开该页面时小程序应该断开同闲聊服务器的
连接。所以我们用小程序的start()和stop()方法断开和关闭套
接口。
Chat.java:
import java.applet.Applet;
import java.awt.*;
import java.net.Socket;
public class Chat extends Applet
{
TextArea ta;
TextField tf;
Socket s;
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);
} catch(Exception e) {
ta.appendText("applet error: "+e+"\n");
}
}
public void stop() {
try {
s.close();
} catch(Exception e) {
ta.appendText("applet error: "+e+"\n");
}
}
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;
}
}
index.html:
<body bgcolor="#FFFFFF">
<applet code="Chat" width=600 height=400>
<param name=host value="somewhere.hotwired.com">
<param name=port value="2323">
[Chat applet]
</applet>
</body>