importjava.applet.*;
importjava.awt.*;
importjava.io.*;
importjava.net.*;
importjava.awt.event.*;
publicclassChatClientextendsApplet{
protectedbooleanloggedIn;//登入状态
protectedFramecp;//聊天室框架
protectedstaticintPORTNUM=7777;//缺省端口号7777
protectedintport;//实际端口号
protectedSocketsock;
protectedBufferedReaderis;//用于从sock读取数据的BufferedReader
protectedPrintWriterpw;//用于向sock写入数据的PrintWriter
protectedTextFieldtf;//用于输入的TextField
protectedTextAreata;//用于显示对话的TextArea
protectedButtonlib;//登入按钮
protectedButtonlob;//登出的按钮
finalstaticStringTITLE="Chatroomapplet>>>>>>>>>>>>>>>>>>>>>>>>";
protectedStringpaintMessage;//发表的消息
publicChatParameterChat;
publicvoidinit(){
paintMessage="正在生成聊天窗口";
repaint();
cp=newFrame(TITLE);
cp.setLayout(newBorderLayout());
StringportNum=getParameter("port");//呢个参数勿太明
port=PORTNUM;
if(portNum!=null)//书上是portNum==null,十分有问题
port=Integer.parseInt(portNum);
//CGI
ta=newTextArea(14,80);
ta.setEditable(false);//readonlyattribute
ta.setFont(newFont("Monospaced",Font.PLAIN,11));
cp.add(BorderLayout.NORTH,ta);
Panelp=newPanel();
Buttonb;
//forloginbutton
p.add(lib=newButton("Login"));
lib.setEnabled(true);
lib.requestFocus();
lib.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
login();
lib.setEnabled(false);
lob.setEnabled(true);
tf.requestFocus();//将键盘输入锁定再右边的文本框中
}
});
//forlogoutbutton
p.add(lob=newButton("Logout"));
lob.setEnabled(false);
lob.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
logout();
lib.setEnabled(true);
lob.setEnabled(false);
lib.requestFocus();
}
});
p.add(newLabel("输入消息:"));
tf=newTextField(40);
tf.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
if(loggedIn){
//pw.println(Chat.CMD_BCAST+tf.getText());//Chat.CMD....是咩野来?
intj=tf.getText().indexOf(":");
if(j>0)pw.println(Chat.CMD_MESG+tf.getText());
else
pw.println(Chat.CMD_BCAST+tf.getText());
tf.setText("");//勿使用flush()?
}
}
});
p.add(tf);
cp.add(BorderLayout.SOUTH,p);
cp.addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEvente){
//如果执行了setVisible或者dispose,关闭窗口
ChatClient.this.cp.setVisible(false);
ChatClient.this.cp.dispose();
logout();
}
});
cp.pack();//勿明白有咩用?
//将Framecp放在中间
Dimensionus=cp.getSize(),
them=Toolkit.getDefaultToolkit().getScreenSize();
intnewX=(them.width-us.width)/2;
intnewY=(them.height-us.height)/2;
cp.setLocation(newX,newY);
cp.setVisible(true);
paintMessage="Windowshouldnowbevisible";
repaint();
}
//登录聊天室
publicvoidlogin(){
if(loggedIn)return;
try{
sock=newSocket(getCodeBase().getHost(),port);
is=newBufferedReader(newInputStreamReader(sock.getInputStream()));
pw=newPrintWriter(sock.getOutputStream(),true);
}catch(IOExceptione){
showStatus("Can'tgetsocket:"+e);
cp.add(newLabel("Can'tgetsocket:"+e));
return;}
//构造并且启动读入器,从服务器读取数据,输出到文本框中
//这里,长成一个线程来避免锁住资源(lockups)
newThread(newRunnable(){
publicvoidrun(){
Stringline;
try{
while(loggedIn&&((line=is.readLine())!=null))
ta.appendText(line+"\n");
}catch(IOExceptione){
showStatus("我的天啊,掉线了也!!!!");
return;
}
}
}).start();
//假定登录(其实只是打印相关信息,并没有真正登录)
//pw.println(Chat.CMD_LOGIN+"AppletUser");
pw.println(Chat.CMD_LOGIN+"AppletUser");
loggedIn=true;
}
//模仿退出的代码
publicvoidlogout(){
if(!loggedIn)
return;
loggedIn=false;
try{
if(sock!=null)
sock.close();
}catch(IOExceptionign){
//异常处理哦
}
}
//没有设置stop的方法,即使从浏览器跳到另外一个网页的时候
//聊天程序还可以继续运行
publicvoidpaint(Graphicsg){
Dimensiond=getSize();
inth=d.height;
intw=d.width;
g.fillRect(0,0,w,2);
g.setColor(Color.black);
g.drawString(paintMessage,10,(h/2)-5);
}
}
聊天室服务器端
importjava.net.*;
importjava.io.*;
importjava.util.*;
publicclassChatServer{
//聊天室管理员ID
protectedfinalstaticStringCHATMASTER_ID="ChatMaster";
//系统信息的分隔符
protectedfinalstaticStringSEP=":";
//服务器的Socket
protectedServerSocketservSock;
//当前客户端列表
protectedArrayListclients;
//调试标记
protectedbooleanDEBUG=false;
publicChatParameterChat;
//主方法构造一个ChatServer,没有返回值
publicstaticvoidmain(String[]argv){
System.out.println("Chatserver0.1starting>>>>>>>>>>>>>>>>");
ChatServerw=newChatServer();
w.runServer();
System.out.println("***ERROR***Chatserver0.1quitting");
}
//构造和运行一个聊天服务
ChatServer(){
Chat=newChatParameter();
clients=newArrayList();
try{
servSock=newServerSocket(7777);//实有问题拉,不过可能是他自己定义既一个class.
System.out.println("ChatServer0.1listeningonport:"+7777);
}catch(Exceptione){
log("IOExceptioninChatServer.
System.exit(0);
}
}
publicvoidrunServer(){
try{
while(true){
Socketus=servSock.accept();
StringhostName=us.getInetAddress().getHostName();
System.out.println("Accpetedfrom"+hostName);
//一个处理的线程
ChatHandlercl=newChatHandler(us,hostName);
synchronized(clients){
clients.add(cl);
cl.start();
if(clients.size()==1)
cl.send(CHATMASTER_ID,"Welcome!Youarethefirstonehere");
else{
cl.send(CHATMASTER_ID,"Welcome!Youarethelatestof"+
clients.size()+"users.");
}
}
}
}catch(Exceptione){
log("IOExceptioninrunServer:"+e);
System.exit(0);
}
}
protectedvoidlog(Strings){
System.out.println(s);
}
//处理会话的内部的类
protectedclassChatHandlerextendsThread{
//客户端scoket
protectedSocketclientSock;
//读取socket的BufferedReader
protectedBufferedReaderis;
//在socket上发送信息行的PrintWriter
protectedPrintWriterpw;
//客户端出主机
protectedStringclientIP;
//句柄
protectedStringlogin;
publicChatHandler(Socketsock,Stringclnt)throwsIOException{
clientSock=sock;
clientIP=clnt;
is=newBufferedReader(
newInputStreamReader(sock.getInputStream()));
pw=newPrintWriter(sock.getOutputStream(),true);
}
//每一个ChatHandler是一个线程,下面的是他的run()方法
//用于处理会话
publicvoidrun(){
Stringline;
try{
while((line=is.readLine())!=null){
charc=line.charAt(0);//我顶你老母啊,果只Chat.CMD咩xx冇定义扑啊///!!!
line=line.substring(1);
switch(c){
//caseChat.CMD_LOGIN:
case'l':
if(!Chat.isValidLoginName(line)){
send(CHATMASTER_ID,"LOGIN"+line+"invalid");
log("LOGININVALIDfrom:"+clientIP);
continue;
}
login=line;
broadcast(CHATMASTER_ID,login+"joinsus,foratotalof"+
clients.size()+"users");
break;
//caseChat.CMD_MESG:
case'm':
if(login==null){
send(CHATMASTER_ID,"pleaseloginfirst");
continue;
}
intwhere=line.indexOf(Chat.SEPARATOR);
Stringrecip=line.substring(0,where);
Stringmesg=line.substring(where+1);
log("MESG:"+login+"--->"+recip+":"+mesg);
ChatHandlercl=lookup(recip);
if(cl==null)
psend(CHATMASTER_ID,recip+"notloggedin.");
else
cl.psend(login,mesg);
break;
//caseChat.CMD_QUIT:
case'q':
broadcast(CHATMASTER_ID,"Goodbyeto"+login+"@"+clientIP);
close();
return;//ChatHandler结束
//caseChat.CMD_BCAST:
case'b':
if(login!=null)
broadcast(login,line);
else
log("B
default:
log("Unknowcmd"+c+"from"+login+"@"+clientIP);
}
}
}catch(IOExceptione){
log("IOException:"+e);
}finally{
//sock结束,我们完成了
//还不能发送再见的消息
//得有简单的基于命令的协议才行
System.out.println(login+SEP+"AllDone");
synchronized(clients){
clients.remove(this);
if(clients.size()==0){
System.out.println(CHATMASTER_ID+SEP+
"I'msolonelyIcouldcry>>>>>");
}elseif(clients.size()==1){
ChatHandlerlast=(ChatHandler)clients.get(0);
last.send(CHATMASTER_ID,"Hey,youaretalkingtoyourselfagain");
}
else{
broadcast(CHATMASTER_ID,"Therearenow"+clients.size()+"users");
}
}
}
}
protectedvoidclose(){
if(clientSock==null){
log("closewhennotopen");
return;
}
try{
clientSock.close();
clientSock=null;
}catch(IOExceptione){
log("Failureduringcloseto"+clientIP);
}
}
//发送一条消息给用户
publicvoidsend(Stringsender,Stringmesg){
pw.println(sender+SEP+"*>"+mesg);
}
//发送私有的消息
protectedvoidpsend(Stringsender,Stringmsg){
send("<*"+sender+"*>",msg);
}
//发送一条消息给所有的用户
publicvoidbroadcast(Stringsender,Stringmesg){
System.out.println("Broadcasting"+sender+SEP+mesg);
for(inti=0;i
if(DEBUG)
System.out.println("Sendingto"+sib);
sib.send(sender,mesg);
}
if(DEBUG)System.out.println("Donebroadcast");
}
protectedChatHandlerlookup(Stringnick){
synchronized(clients){
for(inti=0;i
if(cl.login.equals(nick))
returncl;
}
}
returnnull;
}
//将ChatHandler对象转换成一个字符串
publicStringtoString(){
return"ChatHandler["+login+"]";
}
}
}
publicclassChatParameter{
publicstaticfinalcharCMD_BCAST='b';
publicstaticfinalcharCMD_LOGIN='l';
publicstaticfinalcharCMD_MESG='m';
publicstaticfinalcharCMD_QUIT='q';
publicstaticfinalcharSEPARATOR=':';//?????
publicstaticfinalintPORTNUM=7777;
publicbooleanisValidLoginName(Stringline){
if(line.equals("CHATMASTER_ID"))
returnfalse;
returntrue;
}
publicvoidmain(String[]argv){
}
}
以上代码由于界面限制的原因可能有点儿乱
把它整个复制出去重新整理修改一下就行了
参考资料:CSDN社区