版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
客户端程序:importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;import.*;importjava.io.*;importjava.util.*;publicclassChatClientextendsJFrameimplementsActionListener{JFrameframe=newJFrame("T923-1-29-闫龙-客户端");JPanelpanelLogin;JPanelpanelBack;JPanelpanelTalk;JLabellabelServerIP;JLabellabelName;JLabellabelPassword;JTextAreatextViewTalk;//显示聊天内容的文本区JLabellabelTalk;JLabellabelTo;JTextFieldtextTalk;JTextFieldtextServerIP;//输入服务器IPJTextFieldtextName;//输入用户名JPasswordFieldtextPassword;//输入密码JButtonbuttonTalk;//发送按钮JButtonbuttonLogin;//登录按钮JButtonbuttonReg;//注册按钮JComboBoxlistOnline;GridBagLayoutgl;BorderLayoutbdl;GridBagConstraintsgbc;JDialogdialogLogin=newJDialog(this,"登陆",true);Socketsocket;//定义客户端套接字BufferedReaderin;//定义输入流PrintWriterout;//定义输出流StringstrSend,strReceive,strKey,strStatus;privateStringTokenizerst;publicChatClient(){//初始化gl=newGridBagLayout();bdl=newBorderLayout();gbc=newGridBagConstraints();panelBack=(JPanel)getContentPane();panelBack.setLayout(bdl);panelLogin=newJPanel();panelLogin.setLayout(gl);//初始化控件labelServerIP=newJLabel("服务器IP:");labelName=newJLabel(" 用户名:");labelPassword=newJLabel("密码: ");textServerIP=newJTextField(12);textName=newJTextField(12);textPassword=newJPasswordField(12);buttonLogin=newJButtonC登陆");buttonTalk=newJButton('发送");buttonReg=newJButton('注册");labelTalk=newJLabel('发言:");labelTo=newJLabel("To:");textTalk=newJTextField(30);panelTalk=newJPanel();textViewTalk=newJTextArea(18,40);listOnline=newJComboBox();textViewTalk.setForeground(Color.blue);buttonLogin.addActionListener(this);buttonTalk.addActionListener(this);buttonReg.addActionListener(this);listOnline.addItem("All");〃在线用户列表panelTalk.add(labelTalk);panelTalk.add(textTalk);panelTalk.add(labelTo);panelTalk.add(listOnline);panelTalk.add(buttonTalk);panelBack.add("Center",textViewTalk);panelBack.add("South",panelTalk);panelTalk.setBackground(Color.green);buttonTalk.setEnabled(false);frame.getContentPane().add(panelBack);frame.setSize(600,450);frame.setVisible(true);frame.setResizable(false);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//登陆对话框初始化dialogLogin.getContentPane().setLayout(newFlowLayout());dialogLogin.getContentPane().add(labelServerIP);dialogLogin.getContentPane().add(textServerIP);dialogLogin.getContentPane().add(labelName);dialogLogin.getContentPane().add(textName);dialogLogin.getContentPane().add(labelPassword);dialogLogin.getContentPane().add(textPassword);dialogLogin.getContentPane().add(buttonLogin);dialogLogin.getContentPane().add(buttonReg);dialogLogin.setBounds(300,300,250,200);dialogLogin.getContentPane().setBackground(Color.yellow);dialogLogin.show();}publicstaticvoidmain(String[]args){newChatClient();}//建立与服务端通信的套接字voidconnectServer(){try{socket=newSocket(textServerIP.getText(),8049);in=newBufferedReader(newlnputStreamReader(socket.getlnputStream()));〃初始化输入流out=new PrintWriter(new BufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);〃初始化输出流}catch(ConnectExceptione){JOptionPane.showMessageDialog(this,"连接服务器失败!","ERROE",JOptionPane.INFORMATION_MESSAGE);textServerlP.setText("");System.out.println(e);}catch(Exceptione){System.out.println(e);//弹出窗口publicvoidpopWindows(StringstrWarning,StringstrTitle){JOptionPane.showMessageDialog(this,strWarning,strTitle,JOptionPane.INFORMATION_MESSAGE);}privatevoidinitLogin()throwsIOException{strReceive=in.readLine();//接收信息st=newStringTokenizer(strReceive,"|");/份解信息strKey=st.nextToken();if(strKey.equals("login")){strStatus=st.nextToken();if(strStatus.equals("succeed")){buttonLogin.setEnabled(false);buttonTalk.setEnabled(true);panelLogin.setVisible(false);dialogLogin.dispose();newClientThread(socket);out.println("init|online");〃向服务器发送初始化}popWindows(strKey+""+strStatus+"!","Login");}if(strKey.equals("warning")){strStatus=st.nextToken();popWindows(strStatus,"Register");}}publicvoidactionPerformed(ActionEventevt){Objectobj=evt.getSource();try{if(obj==buttonLogin){//登录if((textServerIP.getText().length()>0)&&(textName.getText().length()>0)&&(textPassword.getText().length()>0)){connectServer();strSend ="login|"+textName.getText()+"|"+String.valueOf(textPassword.getPassword());out.println(strSend);initLogin();}else{popWindows("请输入完整信息","ERROE");}}elseif(obj==buttonReg){//注册if((textName.getText().length()>0)&&(textPassword.getText().length()>0)){connectServer();strSend="reg|"+textName.getText()+"|"+String.valueOf(textPassword.getPassword());out.println(strSend);initLogin();}}elseif(obj==buttonTalk){//发送信息if(textTalk.getText().length()>0){out.println("talk|"+textTalk.getText()+"|"+textName.getText()+"|"+listOnline.getSelectedItem().toString());//textTalk.setText("");}}}catch(Exceptione){System.out.println(e);}}classClientThreadimplementsRunnable{//客户端线程privateSocketsocket;privateBufferedReaderin;privatePrintWriterout;privateStringstrReceive,strKey;privateThreadthreadTalk;privateStringTokenizerst;publicClientThread(Sockets)throwsIOException{this.socket=s;in=newBufferedReader(newInputStreamReader(socket.getInputStream()));threadTalk=newThread(this);threadTalk.start();}publicvoidrun(){while(true){synchronized(this){try{strReceive=in.readLine();st=newStringTokenizer(strReceive,"|");strKey=st.nextToken();if(strKey.equals("talk")){StringstrTalk=st.nextToken();strTalk=textViewTalk.getText()+"\r\n"+strTalk;textViewTalk.setText(strTalk);}elseif(strKey.equals("online")){StringstrOnline;while(st.hasMoreTokens()){strOnline=st.nextToken();listOnline.addltem(strOnline);//加入在线列表}}elseif(strKey.equals("remove")){StringstrRemove;while(st.hasMoreTokens()){strRemove=st.nextToken();listOnline.removeltem(strRemove);}}elseif(strKey.equals("warning")){StringstrWarning=st.nextToken();popWindows(strWarning,"Warning");}Thread.sleep(1000);}catch(lnterruptedExceptione){}catch(lOExceptione){}}服务器端程序:importjava.awt.event.*;importjava.io.*;import.*;importjava.util.*;publicclassChatServer{ServerSocketserverSocket;//创建服务器端套接字privatefinalintSERVER_PORT=8049;//定义端口号publicChatServer(){try{serverSocket=newServerSocket(SERVER_PORT);//启动服务System.out.println("Serverstarted...");System.out.println("Serverportis:"+SERVER_PORT);getIP();//得到并显示服务器端IPwhile(true){Socketsocket=serverSocket.accept();//监听客户端的连接请求,并返回客户端socketnewServerThread(socket);//创建一个新线程来处理与该客户的通讯}}catch(IOExceptione){System.out.println("[ERROR]Coundnotstartserver."+e);}}//得到服务器IP地址并显示publicvoidgetIP(){try{InetAddresslocalAddress=InetAddress.getLocalHost();byte[]ipAddress=localAddress.getAddress();System.out.println("ServerIPis:"+(ipAddress[0]&0xff)+"."+(ipAddress[1]&0xff)+"."+(ipAddress[2]&0xff)+"."+(ipAddress[3]&0xff));}catch(Exceptione){System.out.println("[ERROR]CoundnotgetIP."+e);}//实例化服务器端程序publicstaticvoidmain(Stringargs[]){newChatServer();}}〃接收到客户端socket发来的信息后进行解析、处理、转发classServerThreadextendsThread{privateSocketsocket;//定义客户端套接字privateBufferedReaderin;//定义输入流privatePrintWriterout;//定义输出流privatestaticVectoronlineUser=newVector(10,5);privatestaticVectorsocketUser=newVector(10,5);privateStringstrReceive,strKey;privateStringTokenizerst;//拆分信息privatefinalStringUSERLIST_FILE="F:\\java作业\\user.txt";//设定存放用户信息的文件publicServerThread(Socketclient)throwsIOException{socket=client;in=newBufferedReader(newInputStreamReader(socket.getInputStream()));//客户端接收out=new PrintWriter(new BufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);〃客户端输出this.start();}publicvoidrun(){try{while(true){strReceive=in.readLine();〃从客户端接收一条信息后拆分、解析,并执行相应操作st=newStringTokenizer(strReceive,"|");strKey=st.nextToken();if(strKey.equals("login")){login();}elseif(strKey.equals("talk")){talk();elseif(strKey.equals("init")){initClientOnline();}elseif(strKey.equals("reg")){register();}}}catch(IOExceptione){//用户关闭客户端造成此异常,关闭该用户套接字StringleaveUser=closeSocket();System.out.println("[SYSTEM]"+leaveUser+"leavechatroom!");sendAll("talk|>>>"+leaveUser+"退出了聊天室。");}}//判断是否有该注册用户privatebooleanisExistUser(Stringname){StringstrRead;createtry{createFileInputStreaminputfile=newFileInputStream(USERLIST_FILE);//inputstreamDataInputStreaminputdata=newDataInputStream(inputfile);while((strRead=inputdata.readLine())!=null){StringTokenizerstUser=newStringTokenizer(strRead,"|");if(stUser.nextToken().equals(name)){returntrue;}}}catch(FileNotFoundExceptionfn){System.out.println("[ERROR]UserFilehasnotexist!"+fn);out.println("warning|读写文件时出错!");}catch(IOExceptionie){System.out.println("[ERROR]"+ie);out.println("warning|读写文件时出错!");}returnfalse;}//判断用户的用户名密码是否正确privatebooleanisUserLogin(Stringname,Stringpassword){StringstrRead;try{FileInputStreaminputfile=newFileInputStream(USERLIST_FILE);//createinputstreamDataInputStreaminputdata=newDataInputStream(inputfile);while((strRead=inputdata.readLine())!=null){if(strRead.equals(name+"|"+password)){returntrue;}}}catch(FileNotFoundExceptionfn){System.out.println("[ERROR]UserFilehasnotexist!"+fn);out.println("warning|读写文件时出错!");}catch(IOExceptionie){System.out.println("[ERROR]"+ie);out.println("warning|读写文件时出错!");}returnfalse;}//用户注册privatevoidregister()throwsIOException{Stringname=st.nextToken();//得到用户名称Stringpassword=st.nextToken().trim();//得到用户密码if(isExistUser(name)){System.out.println("[ERROR]"+name+"Registerfail!");out.println("warning|该用户已存在,请改名!");}else{RandomAccessFileuserFile=newRandomAccessFile(USERLIST_FILE,"rw");userFile.seek(userFile.length());//在文件尾部加入新用户信息userFile.writeBytes(name+"|"+password+"\r\n");longin(name);//自动登陆聊天室}}//用户登陆(从登陆框直接登陆)privatevoidlogin()throwsIOException{Stringname=st.nextToken();//得到用户名称Stringpassword=st.nextToken().trim();//得到用户密码booleansucceed=false;System.out.println("[USERLOGIN]"+name+":"+password+":"+socket);for(inti=0;i<onlineUser.size();i++){if(onlineUser.elementAt(i).equals(name)){System.out.println("[ERROR]"+name+"islogined!");out.println("warning|"+name+"已经登陆聊天室");}}if(isUserLogin(name,password)){//判断用户名和密码longin(name);succeed=true;}if(!succeed){out.println("warning|"+name+"登陆失败,请检查您的输入!");System.out.println("[SYSTEM]"+name+"loginfail!");}}//用户登陆privatevoidlongin(Stringname)throwsIOException{out.println("login|succeed");sendAll("online|"+name);//告知每个用户上线列表onlineUser.addElement(name);socketUser.addElement(socket);sendAll("talk|>>>"+name+"进入聊天室!");System.out.println("[SYSTEM]"+name+"loginsucceed!");}//聊天信息处理privatevoidtalk()throwsIOException{StringstrTalkInfo=st.nextToken();//得到聊天内容;StringstrSender=st.nextToken();//得到发消息人StringstrReceiver=st.nextToken();//得到接收人System.out.println("[TALK_"+strReceiver+"]"+strTalkInfo);SocketsocketSend;PrintWriteroutSend;//得到当前时间GregorianCalendarcalendar=newGregorianCalendar();String strTime ="("+calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND)+")";strTalkInfo+=strTime;if(strReceiver.equals("AII")){〃查看是否是发给所有人sendAII("talk|"+strSender+"对所有人说:"+strTaIklnfo);〃调用函数发送}eIse{if(strSender.equaIs(strReceiver)){//是否发给自己out.println("talk|>>>不能向自己发送信息!");}eIse{for(inti=O;i<onIineUser.size();i++){〃循环查找接收者if(strReceiver.equaIs(onIineUser.eIementAt(i))){socketSend=(Socket)socketUser.eIementAt(i);outSend=newPrintWriter(newBufferedWriter(newOutputStreamWriter(socketSend.getOutputStream())),true);outSend.printIn("taIk|"+
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 福建师范大学《劳动和社会保障法》2022-2023学年第一学期期末试卷
- 2024-2030年全球与中国元素杂质分析市场运营现状及前景趋势预测报告
- 涉企经营许可事项告知承诺书(印刷经营许可证核发及变更事项审批)
- 幼儿进餐入厕睡眠观察记录表
- 2024届新疆阿克苏市第一师高级中学高三第二次联考数学试题文试题
- 2024年兰州道路客运输从业资格证培训资料
- 2024年北京客运资格证的要求
- 2024年南京客运考试模拟题及答案详解
- 2024年呼和浩特客运资格证实操考试题目内容是什么
- 2025届浙江省之江教育评价数学高三上期末复习检测试题含解析
- 国有企业共青团创新工作方法研究
- 建筑行业(建筑工程)建设项目设计方案规模划分表.doc
- 办理营业执照委托书
- 集装箱设计PPT课件
- 道路交通标志与标线PPT课件
- 实习实训报告-垫片复合冲压模具的设计
- 35kv变电所电气部分设计(有设计源图)
- 编写标准必备文件 国家标准 地方标准 行业标准 企业标准 格式模板大全
- 全面预算实施方案(共8篇)
- 天津市南开中学2020-2021学年高一上学期期中考试物理试题含答案
- 建设工程施工劳务分包合同(地坪)(完整版)
评论
0/150
提交评论