欢迎来到天天文库
浏览记录
ID:40490904
大小:19.58 KB
页数:5页
时间:2019-08-03
《SimpleChatRoom(简易聊天室代码)》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、packagetest3;//服务器类importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.ArrayList;importjava.util.Iterator;publicclassVerySimpleChatServer{ArrayListclientOutputStream;publicclassClientHandlerim
2、plementsRunnable{BufferedReaderreader;Socketsock;publicClientHandler(SocketclientSocket){try{sock=clientSocket;InputStreamReaderisReader=newInputStreamReader(sock.getInputStream());reader=newBufferedReader(isReader);}catch(Exceptione){e.printStackTrace();}}publicvoidrun(){Stringmessage;try{wh
3、ile((message=reader.readLine())!=null){System.out.println("read"+message);tellEveryone(message);}}catch(Exceptione){e.printStackTrace();}}}publicvoidgo(){clientOutputStream=newArrayList();try{ServerSocketserverSock=newServerSocket(5000);while(true){SocketclientSocket=serverSock.accept();Print
4、Writerwriter=newPrintWriter(clientSocket.getOutputStream());clientOutputStream.add(writer);Threadt=newThread(newClientHandler(clientSocket));t.start();System.out.println("gotaconnection");}}catch(Exceptione){e.printStackTrace();}}publicvoidtellEveryone(Stringmessage){Iteratorit=clientOutputSt
5、ream.iterator();while(it.hasNext()){try{PrintWriterwriter=(PrintWriter)it.next();writer.println(message);writer.flush();}catch(Exceptione){e.printStackTrace();}}}publicstaticvoidmain(String[]args){newVerySimpleChatServer().go();}}packagetest3;//聊天室类importjava.awt.BorderLayout;importjava.awt.e
6、vent.ActionEvent;importjava.awt.event.ActionListener;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JPanel;importjavax.swing.JScrollPane
7、;importjavax.swing.JTextArea;importjavax.swing.JTextField;importjavax.swing.ScrollPaneConstants;publicclassSimpleChatClient{JTextAreainput;JTextFieldoutput;BufferedReaderreader;PrintWriterwriter;Socketsock;publicvoidgo(){JFrameframe=newJFrame
此文档下载收益归作者所有