資源描述:
《客戶端帶聊天記錄》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫。
1、packageGroupChat;importjava.awt.Button;importjava.awt.Color;importjava.awt.Frame;importjava.awt.BorderLayout;//importjava.awt.Label;importjava.awt.Panel;importjava.awt.TextArea;importjava.awt.TextField;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importj
2、ava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;import
3、java.net.ConnectException;importjava.net.Socket;importjava.net.SocketException;importjava.text.SimpleDateFormat;importjava.util.Date;publicclassclientextendsFrame{Framef;Stringclient_name=null;finalTextAreadsp=newTextArea();finalTextFieldmsg=newTextField();Panelp=newPanel();But
4、tonb=newButton("Sent");Socketclient=newSocket();//客戶端socketbooleanconnected=false;BufferedReaderin;PrintWriterout;SimpleDateFormatsdf=newSimpleDateFormat("HH:mm:ss");//設(shè)置時(shí)間格式為時(shí)分秒publicvoiddisconnect()//連接終止時(shí)關(guān)閉流信息和socket{try{out.close();in.close();connected=false;client.close();
5、}catch(NullPointerExceptione){e.printStackTrace();}catch(IOExceptione1){//TODOAuto-generatedcatchblocke1.printStackTrace();}}publicvoidconnect()//與服務(wù)器端取得連接{try{client=newSocket("127.0.0.1",8885);//獲得用戶端socket上的流信息in=newBufferedReader(newInputStreamReader(client.getInputStream()
6、));out=newPrintWriter(client.getOutputStream());connected=true;System.out.println("connected");}catch(ConnectExceptionconnExc){System.err.println("服務(wù)器連接失敗?。?!");}catch(IOExceptione){e.printStackTrace();}}classMyThreadimplementsRunnable//建立線程讀取信息{booleanbconnected;MyThread(boolea
7、ncon){bconnected=con;}publicvoidrun(){Stringread=null;while(bconnected){try{read=in.readLine();//讀取客戶端的流信息,有內(nèi)容讀入,無內(nèi)容掛起System.out.println(read+"hasreceived~");//寫到txt文件,保存聊天記錄Filefile=newFile("D:\"+client_name+"的聊天記錄.txt");if(!file.exists()){file.createNewFile();}FileWriterfwri
8、ter=newFileWriter(file,true);//獲得文件的輸出流,追加方式BufferedWr