JAVA聊天室源码.docx
《JAVA聊天室源码.docx》由会员分享,可在线阅读,更多相关《JAVA聊天室源码.docx(18页珍藏版)》请在冰豆网上搜索。
![JAVA聊天室源码.docx](https://file1.bdocx.com/fileroot1/2023-1/9/67ce9a13-1f9f-46a7-9449-6f7f038cd3eb/67ce9a13-1f9f-46a7-9449-6f7f038cd3eb1.gif)
JAVA聊天室源码
//聊天室服务器
import.*;
importjava.io.*;
importjava.util.*;
importjava.awt.event.*;
importjava.awt.*;
importjavax.swing.*;
classServerextendsJFrame{
privateTextAreamsgA=newTextArea();//服务器用来输入的文本域
privateTextAreaarea=newTextArea();//服务器显示消息的文本域
privateTextFieldportT=newTextField("8888");
privatejava.awt.Listlist=newjava.awt.List();//在线客户列表
privateServerSocketserver;//服务器
privateSocketclient;//客户端
privateMapcontainer=newHashMap();//HashMap
voidinit(){
//设置几个面板//
Panelp1=newPanel();
Panelp2=newPanel();
Panelp3=newPanel();
Panelp4=newPanel();
Panelp5=newPanel();
Panelp6=newPanel();
Panelp7=newPanel();
Panelp8=newPanel();
Panelp9=newPanel();
Panelp10=newPanel();
//设置两个主要的文本框
Labellb1=newLabel("服务器界面");
lb1.setBackground(newColor(250,120,150));
Labellb2=newLabel("port");
BorderLayoutborder1=newBorderLayout();
p1.setLayout(border1);
p1.add(BorderLayout.CENTER,area);
BorderLayoutborder2=newBorderLayout();
p5.setLayout(border2);
p5.add(BorderLayout.NORTH,p3);
p5.add(BorderLayout.CENTER,msgA);
BorderLayoutborder3=newBorderLayout();
p7.setLayout(border3);
p7.add(BorderLayout.CENTER,p1);
p7.add(BorderLayout.SOUTH,p5);
p7.setBackground(newColor(250,150,200));
JButtonstartButton=newJButton("启动服务");
JButtonsendButton=newJButton("发送");
JButtonflushButton=newJButton("刷新列表");
FlowLayoutfl=newFlowLayout(FlowLayout.LEFT);
p8.setLayout(fl);
p8.add(lb2);
p8.add(portT);
p8.add(startButton);
p8.add(sendButton);
p8.add(flushButton);
p8.setBackground(newColor(250,120,150));
BorderLayoutborder4=newBorderLayout();
p9.setLayout(border4);
p9.add(BorderLayout.CENTER,p7);
p9.add(BorderLayout.SOUTH,p8);
p10.setLayout(newBorderLayout());
Labellb3=newLabel("在线用户");
lb3.setBackground(newColor(250,120,150));
p10.add(lb3,BorderLayout.NORTH);
p10.add(list,BorderLayout.CENTER);
area.setEditable(false);
BorderLayoutborder=newBorderLayout();
this.addWindowListener(newWindowAdapter(){
publicvoidwindowClosing(WindowEventarg0){
System.exit(0);
}
});
this.setLayout(border);
this.add(BorderLayout.NORTH,lb1);
this.add(BorderLayout.CENTER,p9);
this.add(BorderLayout.EAST,p10);
this.setTitle("聊天服务器");
this.setBounds(100,100,600,550);
this.setVisible(true);
//"启动服务"按钮监听器
startButton.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
Threadt=newStart();
t.start();
}
});//启动按钮监听器----end
//发送按钮监听器
sendButton.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
Stringmsg=msgA.getText();
if(msg!
=null&&msg!
=""){//如果消息不为空
Calendarca=newGregorianCalendar();
inthh=ca.get(Calendar.HOUR_OF_DAY);
intmm=ca.get(Calendar.MINUTE);
intss=ca.get(Calendar.SECOND);
Stringtime=newString(hh+":
"+mm+":
"+ss+"");
broadcast(time+"[系统消息]:
"+msg);//那么广播这条系统消息
area.append(time+"[系统消息]:
"+msg+"\n");
msgA.setText("");
}
}
});//end
//刷新按钮监听器
flushButton.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
if(list!
=null){
list.removeAll();//清空在线用户列表,以便刷新
}
Set>mySet=container.entrySet();
for(Iterator>it=mySet.iterator();it.hasNext();){//刷新列表
Map.Entryme=it.next();
StringaClientName=me.getKey();
SocketaClient=me.getValue();
StringaClientAddress=aClient.getInetAddress().getHostAddress();
list.add(aClientName+"----"+aClientAddress);
}//endoffor
}//endofactionPerformed
});//end
msgA.addKeyListener(newKeyAdapter(){//键盘监听器---按下Enter发送信息
publicvoidkeyPressed(KeyEvente){
intvalue=e.getKeyCode();
if(value==KeyEvent.VK_ENTER){
Stringmsg=msgA.getText();
Calendarca=newGregorianCalendar();
inthh=ca.get(Calendar.HOUR_OF_DAY);
intmm=ca.get(Calendar.MINUTE);
intss=ca.get(Calendar.SECOND);
Stringtime=newString(hh+":
"+mm+":
"+ss+"");
broadcast(time+"[系统消息]:
"+msg);//那么广播这条系统消息
area.append(time+"[系统消息]:
"+msg+"\n");
msgA.setText("");
}
}
});
}//endofinit()
classStartextendsThread//启动服务器的线程
{
publicvoidrun(){
try{
if(server!
=null&&!
server.isClosed()){
area.append("警告!
服务器已在启动中!
\n");
}
else{
server=newServerSocket(Integer.parseInt(portT.getText()));//启动服务器
area.append((newDate()).toString()+'\n'+"[恭喜!
^_^]"+"服务器启动成功!
"+"\n\n");
}
while(true){
client=server.accept();
ThreadsgS=newSgService(client);//为每位登录的客户创建一个线程
sgS.start();//启动客户线程
}
}
catch(Exceptione){
System.out.println("cuowu1");
e.printStackTrace();
}
}//endofrun()
}//endofStart
//处理单个客户的线程
classSgServiceextendsThread//SgService---begin
{
privateSocketclient=null;//客户套接字
privateBufferedReaderbr=null;//输入流
privatePrintStreamps=null;
privateintcounter=0;//记录是第几次接受用户的信息
privateintmark=0;//记录用户说不文明用语的次数
privateStringname=null;
SgService(Socketclient){//构造方法
this.client=client;
publicvoidrun(){//run()----begin
try{
br=newBufferedReader(newInputStreamReader(client.getInputStream()));
ps=newPrintStream(client.getOutputStream());
Stringmsg=null;
while((msg=br.readLine())!
=null){//无限循环,意味着可以和客户进行无限次交互
if(counter==0){
name=msg;
container.put(name,client);
list.add(name+"----"+client.getInetAddress().getHostAddress());
Calendarca=newGregorianCalendar();
inthh=ca.get(Calendar.HOUR_OF_DAY);
intmm=ca.get(Calendar.MINUTE);
intss=ca.get(Calendar.SECOND);
Stringtime=hh+":
"+mm+":
"+ss+"";
broadcast(time+name+"上线了!
");
area.append(time+name+"上线了!
\n\n");
counter++;
}
else{
if(msg.equals("你是个笨蛋")){
mark=mark+1;
if(mark<3){
Calendarca=newGregorianCalendar();
inthh=ca.get(Calendar.HOUR_OF_DAY);
intmm=ca.get(Calendar.MINUTE);
intss=ca.get(Calendar.SECOND);
Stringtime=newString(hh+":
"+mm+":
"+ss+"");
singleCom(time+"[系统消息]:
警告!
请注意文明用语!
",client);
//在服务器端显示这个用户说不文明语言的次数
area.append(time+"[系统消息]:
"+name+"第"+mark+"次使用了不文明用语,特此警告!
");
}
else{//如果客户第三次说不文明的话,系统就把他踢出聊天室
Calendarca=newGregorianCalendar();
inthh=ca.get(Calendar.HOUR_OF_DAY);
intmm=ca.get(Calendar.MINUTE);
intss=ca.get(Calendar.SECOND);
Stringtime=newString(hh+":
"+mm+":
"+ss+"");
if(mark==3){
singleCom(time+"[系统消息]:
由于您多次使用了不文明用语,经警告无效,现已被踢出聊天室!
",client);//告诉他本人
}
removeClient(name,client);//从系统列表中删除这个人的信息
//并向所有人广播这一消息
broadcast(time+"[系统消息]:
"+name+"由于多次使用了不文明用语,经警告无效,现已被踢出聊天室!
");
area.append(time+"[系统消息]:
"+name+"由于多次使用了不文明用语,经警告无效,现已被踢出聊天室!
\n");
}
}
else{
Calendarca=newGregorianCalendar();
inthh=ca.get(Calendar.HOUR_OF_DAY);
intmm=ca.get(Calendar.MINUTE);
intss=ca.get(Calendar.SECOND);
Stringtime=newString(hh+":
"+mm+":
"+ss+"");
area.append(time+name+"说:
"+msg+"\n\n");//将客户发送的消息显示在服务器的窗口中
broadcast(time+name+"说:
"+msg+"\n");//同时向每个在线客户广播这则消息
}
}
}//endofwhile
}
catch(Exceptionex){
Calendarca=newGregorianCalendar();
inthh=ca.get(Calendar.HOUR_OF_DAY);
intmm=ca.get(Calendar.MINUTE);
intss=ca.get(Calendar.SECOND);
Stringtime=newString(hh+":
"+mm+":
"+ss+"");
area.append(time+name+"下线了!
\n");
broadcast(time+name+"下线了!
\n");
list.remove(name+"----"+client.getInetAddress().getHostAddress());
container.remove(name);
}
}//run()---end
}//SgService-----end
voidremoveClient(Stringname,Socketclient){//踢人
list.remove(name+"----"+client.getInetAddress().getHostAddress());
container.remove(name);
}
//广播
voidbroadcast(Stringmsg){//broadcast()-----begin
Set>mySet=container.entrySet();
Iterator>it=mySet.iterator();
Stringmessage=msg;
while(it.hasNext()){//如果列表中还有客户
Map.Entryme=it.next();
SockettempClient=me.getValue();
singleCom(message,tempClient);//就把消息向发给这个客户
}
}//broadcast()-----end
//向单个客户发送消息
privatevoidsingleCom(Stringmsg,SocketaClient){//singleCommunication------begin
try{
PrintStreampw=newPrintStream(aClient.getOutputStream());
Stringmessage=msg;
pw.println(msg);
}catch(Exceptionex){
ex.printStackTrace();
}
}//singleCommunication----end
publicstaticvoidmain(String[]args){
newServer().init();//启动服务器窗口
System.out.println("服务器:
");
}
}//endofServer
//登录界面:
importjavax.swing.*;
importjava.awt.*;
importjava.awt.event.*;
importjava.io.*;
import.*;
classLoginextendsJFrameimplementsActionListener
{
TextFieldtxtPort;
TextFieldtxtIP;
TextFieldtxtName;
JButtonbtnLogin;
JButtonbtnCancel;
SockettoServer;
BufferedReaderin;
PrintStreamout;
publicLogin(){
Panelp1=newPanel();
Panelp2=newPanel();
Panelp3=newPanel();
Panelp4=newPanel();
Panelp5=newPanel();
Labell1=newLabel("port");
Labell2=newLabel("IP");
Labell3=newLabel("昵称");
txtPort=newTextField("8888",15);
txtIP=newTextField("192.168.55.1",15);
txtName=newTextField("小敏",15);
p2.add(l1);
p2.add(txtPort);
p3.add(l2);
p3.add(txtIP);
p4.add(l3);
p4.add(txtName);
GridLayoutg=newGridLayout(3,1);//三行一列的网格布局管理器
p1.setLayout(g);//设置布局管理器
p1.add(p2);//将组件添加到面板中
p1.add(p3);
p1.add(p4);
p1.setBackground(newColor(100,250,100));//更改面板颜色
btnLogin=newJButton("登陆");
btnCancel=newJButton("取消");
btnLogin.addActionListener(this);//添加监听器
btnCancel.addActionListener(this);
BorderLayoutborder1=newBorderLayout();//边界布局管理器
this.setLayout(border1);
p5.add(btnLogin);
p5.add(btnCan