有登陸界面的聊天室程序_第1頁
有登陸界面的聊天室程序_第2頁
有登陸界面的聊天室程序_第3頁
有登陸界面的聊天室程序_第4頁
有登陸界面的聊天室程序_第5頁
已閱讀5頁,還剩7頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

客戶端程序: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;//顯示聊天內(nèi)容的文本區(qū)JLabellabelTalk;JLabellabelTo;JTextFieldtextTalk;JTextFieldtextServerIP;//輸入服務(wù)器IPJTextFieldtextName;//輸入用戶名JPasswordFieldtextPassword;//輸入密碼JButtonbuttonTalk;//發(fā)送按鈕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("服務(wù)器IP:");labelName=newJLabel(" 用戶名:");labelPassword=newJLabel("密碼: ");textServerIP=newJTextField(12);textName=newJTextField(12);textPassword=newJPasswordField(12);buttonLogin=newJButtonC登陸");buttonTalk=newJButton('發(fā)送");buttonReg=newJButton('注冊");labelTalk=newJLabel('發(fā)言:");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();}//建立與服務(wù)端通信的套接字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,"連接服務(wù)器失敗!","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");〃向服務(wù)器發(fā)送初始化}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){//發(fā)送信息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){}}服務(wù)器端程序:importjava.awt.event.*;importjava.io.*;import.*;importjava.util.*;publicclassChatServer{ServerSocketserverSocket;//創(chuàng)建服務(wù)器端套接字privatefinalintSERVER_PORT=8049;//定義端口號publicChatServer(){try{serverSocket=newServerSocket(SERVER_PORT);//啟動(dòng)服務(wù)System.out.println("Serverstarted...");System.out.println("Serverportis:"+SERVER_PORT);getIP();//得到并顯示服務(wù)器端IPwhile(true){Socketsocket=serverSocket.accept();//監(jiān)聽客戶端的連接請求,并返回客戶端socketnewServerThread(socket);//創(chuàng)建一個(gè)新線程來處理與該客戶的通訊}}catch(IOExceptione){System.out.println("[ERROR]Coundnotstartserver."+e);}}//得到服務(wù)器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);}//實(shí)例化服務(wù)器端程序publicstaticvoidmain(Stringargs[]){newChatServer();}}〃接收到客戶端socket發(fā)來的信息后進(jìn)行解析、處理、轉(zhuǎn)發(fā)classServerThreadextendsThread{privateSocketsocket;//定義客戶端套接字privateBufferedReaderin;//定義輸入流privatePrintWriterout;//定義輸出流privatestaticVectoronlineUser=newVector(10,5);privatestaticVectorsocketUser=newVector(10,5);privateStringstrReceive,strKey;privateStringTokenizerst;//拆分信息privatefinalStringUSERLIST_FILE="F:\\java作業(yè)\\user.txt";//設(shè)定存放用戶信息的文件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();〃從客戶端接收一條信息后拆分、解析,并執(zhí)行相應(yīng)操作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){//用戶關(guān)閉客戶端造成此異常,關(guān)閉該用戶套接字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|讀寫文件時(shí)出錯(cuò)!");}catch(IOExceptionie){System.out.println("[ERROR]"+ie);out.println("warning|讀寫文件時(shí)出錯(cuò)!");}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|讀寫文件時(shí)出錯(cuò)!");}catch(IOExceptionie){System.out.println("[ERROR]"+ie);out.println("warning|讀寫文件時(shí)出錯(cuò)!");}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);//自動(dòng)登陸聊天室}}//用戶登陸(從登陸框直接登陸)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+"已經(jīng)登陸聊天室");}}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);//告知每個(gè)用戶上線列表onlineUser.addElement(name);socketUser.addElement(socket);sendAll("talk|>>>"+name+"進(jìn)入聊天室!");System.out.println("[SYSTEM]"+name+"loginsucceed!");}//聊天信息處理privatevoidtalk()throwsIOException{StringstrTalkInfo=st.nextToken();//得到聊天內(nèi)容;StringstrSender=st.nextToken();//得到發(fā)消息人StringstrReceiver=st.nextToken();//得到接收人System.out.println("[TALK_"+strReceiver+"]"+strTalkInfo);SocketsocketSend;PrintWriteroutSend;//得到當(dāng)前時(shí)間GregorianCalendarcalendar=newGregorianCalendar();String strTime ="("+calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND)+")";strTalkInfo+=strTime;if(strReceiver.equals("AII")){〃查看是否是發(fā)給所有人sendAII("talk|"+strSender+"對所有人說:"+strTaIklnfo);〃調(diào)用函數(shù)發(fā)送}eIse{if(strSender.equaIs(strReceiver)){//是否發(fā)給自己out.println("talk|>>>不能向自己發(fā)送信息!");}eIse{for(inti=O;i<onIineUser.size();i++){〃循環(huán)查找接收者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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論