版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
2)电子工业出版社《JAVA程序设计实用教程》,叶核亚编著三、设计完成后提交的文件和图表2)电子工业出版社《JAVA程序设计实用教程》,叶核亚编著考资料 3 3 3 3 4 4 5 6 6 8 441.1问题描述发送文件等交流方式已经成为必然潮流。因此出现了QQ等聊天工具,然而QQ等聊1.2功能需求分析和用户号码。可通过闪动托盘图标和播放不同的音乐1.3环境需求分析2.1整体思路2.2总体设计流程图建立服务器等待并接收接收请求后创建socket连接3.1.界面设计3.2通信功能实现方法publicclassAppServerextendsThread{privateServerSocketserverSocket;privateServerFramesFrame;privatestaticVectoruserOnline=newVector(1,1);privatestaticVectorv=newVector(1,1);/***创建服务器启动服务监听1001端口**/publicAppServer(){sFrame=newServerFrame();try{serverSocket=newServerSocket(1001);//获取服务器的主机名和IP地址InetAddressaddress=InetAddress.getLocalHost();sFrame.txtServerName.setText(address.getHostName());sFrame.txtIP.setText(address.getHostAddress());sFrame.txtPort.setText("1001");}catch(IOExceptione){fail(e,"}sFrame.txtStatus.setText("已启动...");this.start();//启动线程}/***退出服务器**异常*退出信息*/publicstaticvoidfail(Exceptione,Stringstr){System.out.println(str+"。"+e);}/***监听客户的请求,当有用户请求时创建Connection线程*/publicvoidrun(){try{while(true){Socketclient=serverSocket.accept();newConnection(sFrame,client,userOnline,v);//支持//System.out.println("userLength:"+userLength);}}catch(IOExceptione){System.out.println("不能监听");}}/***/publicstaticvoidmain(Stringargs[]){newAppServer();}}ServerFrame.java文件publicclassServerFrameextendsJFrameimplementsActionListener{publicJListlist;/****/privatestaticfinallongserialVersionUID=//服务器信息面板JPanelpnlServer,pnlServerInfo;JLabellblStatus,lblNumber,lblMax,lblServerName,lblProtocol,lblIP,lblPort,lblLog;publicJTextFieldtxtStatus,txtNumber,txtMax,txtServerName,txtProtocol,txtIP,txtPort;JButtonbtnStop,btnSaveLog;publicTextAreataLog;JTabbedPanetpServer;publicTextAreataMessage;//用户信息面板JPanelpnlUser;publicJLabellblMessage,lblUser,lblNotice,lblUserCount;JListlstUser;JScrollPanespUser;JTextFieldtxtNotice;JButtonbtnSend,btnKick;publicStringti="";publicStringserverMessage="";publicServerFrame(){//服务器窗口super("[HappyChat]聊天服务器");setSize(550,500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setResizable(false);Dimensionscr=Toolkit.getDefaultToolkit().getScreenSize();//Dimensionfra=this.getSize();if(fra.width>scr.width){fra.width=scr.width;}if(fra.height>scr.height){fra.height=scr.height;}this.setLocation((scr.width-fra.width)/2,(scr.height-fra.height)/2);pnlServer=newJPanel();pnlServer.setLayout(null);pnlServerInfo=newJPanel(newGridLayout(14,1));pnlServerInfo.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(""),BorderFactory.createEmptyBorder(1,1,1,1)));lblStatus=newJLabel("当前状态:");txtStatus=newJTextField(10);txtStatus.setEditable(false);lblNumber=newJLabel("当前在线人数:");txtNumber=newJTextField("0人",10);txtNumber.setEditable(false);lblMax=newJLabel("最多在线人数:");txtMax=newJTextField("50人",10);txtMax.setEditable(false);lblServerName=newJLabel("服务器名称:");JTextField(10);txtServerName.setEditable(false);lblProtocol=newJLabel("访问协议:");txtProtocol=newJTextField("HTTP",10);txtProtocol.setEditable(false);lblIP=newJLabel("服务器IP:");txtIP=newJTextField(10);txtIP.setEditable(false);lblPort=newJLabel("服务器端口:");txtPort=newJTextField("8000",10);txtPort.setEditable(false);btnStop=newJButton("关闭服务器(C)");btnStop.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){closeServer();}});lblLog=newJLabel("[服务器日志]");taLog=newTextArea(20,50);btnSaveLog=newJButton("保存日志(S)");btnSaveLog.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){saveLog();}});pnlServerInfo.add(lblStatus);pnlServerInfo.add(txtStatus);pnlServerInfo.add(lblNumber);pnlServerInfo.add(txtNumber);pnlServerInfo.add(lblMax);pnlServerInfo.add(txtMax);pnlServerInfo.add(lblServerName);pnlServerInfo.add(txtServerName);pnlServerInfo.add(lblProtocol);pnlServerInfo.add(txtProtocol);pnlServerInfo.add(lblIP);pnlServerInfo.add(txtIP);pnlServerInfo.add(lblPort);pnlServerInfo.add(txtPort);pnlServerInfo.setBounds(5,5,100,400);lblLog.setBounds(110,5,100,30);taLog.setBounds(110,35,400,370);btnStop.setBounds(200,410,120,30);btnSaveLog.setBounds(320,410,120,30);pnlServer.add(pnlServerInfo);pnlServer.add(lblLog);pnlServer.add(taLog);pnlServer.add(btnStop);pnlServer.add(btnSaveLog);pnlUser=newJPanel();pnlUser.setLayout(null);lblMessage=newJLabel("[用户消息]");taMessage=newTextArea(20,20);lblNotice=newJLabel("通知:");txtNotice=newJTextField(20);btnSend=newJButton("发送(S)");btnSend.setEnabled(true);btnSend.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){serverMessage();}});lblUserCount=newJLabel("在线总人数0人");btnKick=newJButton("踢人(K)");btnKick.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg0){tiRen();}});lblUser=newJLabel("[在线用户列表]");lstUser=newJList();lstUser.setVisibleRowCount(17);lstUser.setFixedCellWidth(180);//指定的固定单元格宽度值,而不lstUser.setFixedCellHeight(18);spUser=newJScrollPane();spUser.setVerticalScrollBarPolicy(JScrollPane.spUser.getViewport().setView(lstUser);lblMessage.setBounds(5,5,100,25);taMessage.setBounds(5,35,300,360);lblUser.setBounds(310,5,100,25);spUser.setBounds(310,35,220,360);lblNotice.setBounds(5,410,40,25);txtNotice.setBounds(50,410,160,25);btnSend.setBounds(210,410,80,25);lblUserCount.setBounds(320,410,100,25);btnKick.setBounds(440,410,80,25);pnlUser.add(lblMessage);pnlUser.add(taMessage);pnlUser.add(lblUser);pnlUser.add(spUser);list=newJList();list.setListData(newString[]{""});spUser.setViewportView(list);pnlUser.add(lblNotice);pnlUser.add(txtNotice);pnlUser.add(btnSend);pnlUser.add(lblUserCount);pnlUser.add(btnKick);tpServer=newJTtpServer.add("服务器管理",pnlServer);tpServer.add("用户信息管理",pnlUser);this.getContentPane().add(tpServer);setVisible(true);}protectedvoidserverMessage(){this.serverMessage=txtNotice.getText();txtNotice.setText("");}protectedvoidcloseServer(){this.dispose();//this.res}protectedvoidsaveLog(){try{FileOutputStreamfileoutput=newFileOutputStream("log.txt",true);Stringtemp=taMessage.getText();fileoutput.write(temp.getBytes());fileoutput.close();JOptionPane.showMessageDialog(null,"记录保存在log.txt");}catch(Exceptione){System.out.println(e);}}protectedvoidtiRen(){ti=list.getSelectedValue().toString();log("Ti:"+ti);}privatevoidlog(Stringstring){Stringnewta=taMessage.getText();newta+=("\n"+string);taMessage.setText(newta);}publicvoidactionPerformed(ActionEventevt){}publicstaticvoidmain(Stringargs[]){newServerFrame();}}Connection.java文件publicclassConnectionextendsThread{/***与客户端通讯Socket*/privateSocketnetClient;/***在线用户列表*/privateVector<Customer>userOnline;/***聊天信息*/privateVector<Chat>userChat;/***从客户到服务器输入流*/privateObjectInputStreamfromClient;/***传到客户端打印流*/privatePrintStreamtoClient;/***注册用户列表*/privatestaticVectorvList=newVector();/***临时对象*/privateObjectobj;/***服务器日志窗体*/privateServerFramesFrame;@SuppressWarnings("unchecked")/***创建与客户端通讯*/publicConnection(ServerFrameframe,Socketclient,Vectoru,Vectorc){netClient=client;userOnline=u;userChat=c;sFrame=frame;try{fromClient=newObjectInputStream(netClient.getInputStream());toClient=newPrintStream(netClient.getOutputStream());}catch(IOExceptione){try{netClient.close();}catch(IOExceptione1){System.out.println("不能建立流"+e1);return;}}this.start();}/***处理与客户端的通讯线程*/publicvoidrun(){try{//obj是Object类的对象obj=(Object)fromClient.readObject();{if(obj.getClass().getName().equals("Customer")){serverLogin();serverLoginDB();}if(obj.getClass().getName().equals("Register_Customer"))serverRegiste();serverRegisteDB();}if(obj.getClass().getName().equals("Message")){serverMessage();}if(obj.getClass().getName().equals("Chat")){serverChat();}if(obj.getClass().getName().equals("Exit")){serverExit();}}catch(IOExceptione){System.out.println(e);}catch(ClassNotFoundExceptione1){System.out.println("}finally{try{netClient.close();}catch(IOExceptione){System.out.println(e);}}}/****登录处理*/@SuppressWarnings("deprecation")publicvoidserverLogin(){try{CustomerclientMessage2=(Customer)obj;FileInputStreamfile3=newFileInputStream("user.txt");ObjectInputStreamobjInput1=newObjectInputStream(file3);vList=(Vector)objInput1.readObject();intfind=0;//查找判断标志//System.out.println(find);for(inti=0;i<vList.size();i++){Register_Customerreg=(Register_Customer)vList.elementAt(i);if(reg.custName.equals(clientMessage2.custName)){find=1;if(!reg.custPassword.equals(clientMessage2.custPassword)){toClient.println("密码不正确");break;}else{//判断是否已经登录intlogin_flag=0;for(inta=0;a<userOnline.size();a++){String_custName=((Customer)userOnline.elementAt(a)).custName;if(clientMessage2.custName.equals(_custName)){login_flag=1;break;}}if(userOnline.size()>=50){toClient.println("登录人数过多,请稍候再试");break;}if(login_flag==0){clientMessage2.custHead=reg.head;//userOnline.addElement(clientMessage2);toClient.println("登录成功");Datet=newDate();+"登录时间:"+t.toLocaleString()+"\n");freshServerUserList();break;}else{toClient.println("该用户已登录");}}}else{continue;}}if(find==0){toClient.println("没有这个用户,请先注册");}file3.close();objInput1.close();fromClient.close();}catch(ClassNotFoundExceptione){System.out.println(e);}catch(IOExceptione){System.out.println(e);}}/*****@throwsException*/@SuppressWarnings("deprecation")publicvoidserverLoginDB(){try{CustomerclientMessage2=(Customer)obj;Stringname=clientMessaStringpass=clientMessage2.custPassword;+"'";ResultSetrs=DB.executeQuery(sql);System.out.println("sql:"+sql);booleanlogin=false;Stringhead="";while(rs.next()){Stringps=rs.getString("custPassword").toString();System.out.println("ps:["+ps+"]");System.out.println("pass:["+pass+"]");if(ps.equals(pass.toString())){login=true;System.out.println("logined:");}System.out.println("compareTo:"+pareTo(pass));head=rs.getString("head");System.out.println("head:"+rs.getString("head"));}System.out.println("login:"+login);if(!login){toClient.println("密码不正确");return;}//判断是否已经登录intlogin_flag=0;for(inta=0;a<userOnline.size();a++){String_custName=((Customer)userOnline.elementAt(a)).custName;if(clientMessage2.custName.equals(_custName)){login_flag=1;break;}}if(userOnline.size()>=50){toClient.println("登录人数过多,请稍候再试");return;}if(login_flag==0){System.out.println("head:"+head);clientMessage2.custHead=head;//userOnline.addElement(clientMessage2);toClient.println("登录成功");Datet=newDate();登录时间:"+t.toLocaleString()+"\n");freshServerUserList();return;}else{toClient.println("该用户已登录");}fromClient.close();}catch(Exceptione){e.printStackTrace();}}/****/privatevoidfreshServerUserList(){String[]userList=newString[50];Customercus=null;for(intj=0;j<userOnline.size();j++){cus=(Customer)userOnline.get(j);userList[j]=cus.custName;}sFrame.list.setListData(userList);sFrame.txtNumber.setText(""+userOnline.size());sFrame.lblUserCount.setText("当前在线人数:"+userOnline.size());//System.out.println("freshok");}/***/@SuppressWarnings({"unchecked","deprecation"})publicvoidserverRegiste(){try{intflag=0;//是否重名判断标志Register_CustomerclientMessage=(Register_Customer)obj;FilefList=newFile("user.txt");if(fList.length()!=0)//{ObjectInputStreamobjInput=newObjectInputStream(newFileInputStream(fList));vList=(Vector)objInput.readObject();//判断是否有重名for(inti=0;i<vList.size();i++){Register_Customerreg=(Register_Customer)vList.elementAt(i);if(reg.custName.equals(clientMessage.custName)){toClient.println("注册名重复,请另外选择");flag=1;break;}elseif(reg.custName.equals("所有人")){toClient.println("禁止使用此注册名,请另外选择");flag=1;break;}}}if(flag==0){//添加新注册用户vList.addElement(clientMessage);//将向量中的类写回文件FileOutputStreamfile=newFileOutputStream(fList);ObjectOutputStream(file);objout.writeObject(vList);//发送注册成功信息toClient.println(clientMessage.custName+"注册成功");Datet=newDate();log("用户"+clientMessage.custName+"注册成功,"+"注册时间:"+t.toLocaleString()+"\n");file.close();objout.close();fromClient.close();}}catch(ClassNotFoundExceptione){System.out.println(e);}catch(IOExceptione){System.out.println(e);}}/***/@SuppressWarnings({"unchecked","deprecation"})publicvoidserverRegisteDB(){try{intflag=0;//是否重名判断标志Register_CustomerclientMessage=(Register_Customer)obj;Stringsql="select*fromyonghuwherecustName='"+clientMessage.custName+"'";ResultSetrs=DB.executeQuery(sql);System.out.println("sql:"+sql);booleanreg=false;while(rs.next()){reg=true;ResultSetMetaDatarsmd=rs.getMetaData();for(intStringv=rs.getString(i);System.out.println(me+":"+v);}System.out.println();}System.out.println("reg:"+reg);if(reg){toClient.println("注册名重复,请另外选择");return;}if(clientMessage.custName.equals("所有人")){toClient.println("禁止使用此注册名,请另外选择");return;}sql="insertintoyonghu(custName,custPassword,age,sex,email,head)values('"+clientMessage.custName+"','"+clientMessage.custPassword+"','"+clientMessage.age+"','"+clientMessage.sex+"','"+clientMessage.email+"','"+clientMessage.head+"')";System.out.println("c:"+sql);DB.executeUpdate(sql);toClient.println(clientMessage.custName+"注册成功");Datet=newDate();log("用户"+clientMessage.custName+"注册成功,"+"注册时间:"+t.toLocaleString()+"\n");fromClient.close();}catch(Exceptione){e.printStackTrace();System.out.println(e);}}/***发送信息处理*/publicvoidserverMessage(){try{Messagemess=newMessage();mess.userOnLine=userOnline;mess.chat=userChat;mess.ti=sFrame.ti;mess.serverMessage=""+sFrame.serverMessage;ObjectOutputStreamoutputstream=newObjectOutputStream(netClient.getOutputStream());outputstream.writeObject((Message)mess);netClient.close();outputstream.close();}catch(IOExceptione){}}/***增加信息处理*/publicvoidserverChat(){ChatcObj=newChat();cObj=(Chat)obj;cObj.chatMessage=WordFilter.filter(cObj.chatMessage);chatLog(cObj);userChat.addElement((Chat)cObj);return;}/***用户退出处理*/@SuppressWarnings("deprecation")publicvoidserverExit(){Exitex
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
评论
0/150
提交评论