首页 > 代码库 > 线程练习题---简易多人聊天室

线程练习题---简易多人聊天室

 1 package Day_1; 2  3 import java.io.DataInputStream; 4 import java.io.DataOutputStream; 5 import java.io.EOFException; 6 import java.io.IOException; 7 import java.net.ConnectException; 8 import java.net.Socket; 9 import java.net.SocketException;10 import java.net.UnknownHostException;11 import java.util.Scanner;12 13 /*14  * 对于聊天室而言,不需要进行单线程进行即可。15  * 和Socket编程16  * */17 public class Client {18 19     private DataInputStream Dis = null;20     private DataOutputStream Dos = null;21     private boolean connect = false;22     Socket sc = null;23 24     public static void main(String args[]) {25         new Client().start();26     }27 28     private void send(String str) {29         try {30             Dos.writeUTF(str);31         } catch (IOException e) {32             // TODO Auto-generated catch block33             e.printStackTrace();34         }35     }36 37     private void sec() {38         try {39             System.out.println("这是来自服务器:" + sc.getInetAddress() + ": "40                     + Dis.readUTF());41         } catch (EOFException e) {42             System.out.println("该客户端退出了!");43         } catch (IOException e) {44             // TODO Auto-generated catch block45             e.printStackTrace();46         }47     }48 49     public void start() {50         try {51             // 建立连接52             sc = new Socket("127.0.0.1", 8888);53             Dos = new DataOutputStream(sc.getOutputStream());54             Dis = new DataInputStream(sc.getInputStream());55             connect = true; // 可以开始通话了56         } catch (ConnectException e) {57             System.out.println("服务器,木有打开!");58         } catch (IOException e) {59             // TODO Auto-generated catch block60             e.printStackTrace();61         }62         while (connect) {63             Scanner read = new Scanner(System.in);64             while (read.hasNext()) {65                 String st = read.next();66                 if (st.equals("exit")) {67                     try {68                         if (Dos != null)69                             Dos.close();70                         if (Dis != null)71                             Dis.close();72                         if (sc != null)73                             sc.close();74                     } catch (IOException e) {75                         // TODO Auto-generated catch block76                         e.printStackTrace();77                     }78                     connect=false;79                     break;80                 }81                 this.send(st);82                 this.sec();83             }84         }85     }86 }
  1 package Day_1;  2   3 import java.io.DataInputStream;  4 import java.io.DataOutputStream;  5 import java.io.EOFException;  6 import java.io.IOException;  7 import java.net.BindException;  8 import java.net.ServerSocket;  9 import java.net.Socket; 10 import java.util.ArrayList; 11 import java.util.Deque; 12 import java.util.List; 13 import java.util.concurrent.ExecutorService; 14 import java.util.concurrent.Executors; 15    16  17 public class GetPicture { 18      19     /** 20      * @param args 21      * 聊天室有n个人在聊天,聊天服务器就应该为每个进入聊天室的人创建一个对应的线程, 22      * 该线程监听对应的聊天者是否有消息传来。如果有,则向所有的聊天者广播该消息。 23      * 实现该网络聊天系统、 24      */ 25     private boolean started =false; 26     private boolean connect=false; 27     //放置一个链表来存放新建的客户端 28     List<NewClient> list=new ArrayList<NewClient>() ; 29     //设定一个无限制大小的线程池          30     ExecutorService  es = Executors.newCachedThreadPool(); 31     public static  void main(String[] args) { 32         // TODO Auto-generated method stub 33           new GetPicture().start();     34     }     35      36     public void start(){     37         final int port=8888;   38         ServerSocket  ss = null ;     39         try { 40             //创建套接字 41             ss = new ServerSocket(port); 42             connect = true; 43         }catch(BindException e) 44         { 45             //不做任何处理 46         } 47         catch (IOException e) { 48             // TODO Auto-generated catch block 49             e.printStackTrace(); 50         } 51         //如果连接上,则表示不断的创建客户端对象 52         try { 53         while(connect){ 54               //表示不断的监听 55                Socket st =  ss.accept(); 56                //将套接字放进 NewClient类中 57                NewClient nc = new NewClient(st); 58                //将NewClient类放进线程中,创建多线程 59               // new Thread(nc).start();  //创建线程 60                //放进线程池中 61                es.execute(new Thread(nc)); 62                //将newClient放进链表中 63                list.add(nc); 64                System.out.println("客戶端接收成功"); 65             } }catch (IOException e) { 66                 // TODO Auto-generated catch block 67                 e.printStackTrace(); 68             } 69         } 70      71      72  //创建一个新的客户端类 73 class NewClient implements Runnable 74 { 75      DataInputStream   Dis = null; 76      DataOutputStream  Dos = null; 77      Socket sc=null; 78      boolean started=false; //初始断开 79   public NewClient(Socket st){ 80            this.sc=st; 81            try { 82                 //获得对方发过来的缓存数据流 83              Dis = new DataInputStream(st.getInputStream()); 84              Dos = new DataOutputStream(st.getOutputStream()); 85              //如果正常说明,已经接收到了对方的发送过来的数据、 86              started =true; 87         } catch (IOException e) { 88             // TODO Auto-generated catch block 89              e.printStackTrace(); 90         } 91     } 92   public void send(String str) 93   { 94        try { 95            // 将数据写入到对方的内存中 96              Dos.writeUTF(str); 97         } 98        catch(EOFException e){ 99            System.out.println("对方客户端退出了!");100        } catch (IOException e) {101             // TODO Auto-generated catch block102             e.printStackTrace();103         }104   }105   @Override106   public void run() {107      // TODO Auto-generated method stub108       //如果连接上了,就可以提取相应的数据109        String str=null;110        try {111        while(started){112              //采用UTF-8的编码格式进行流的输入输出113                str = Dis.readUTF();114                /*for(int i=0;i<list.size() ;i++){115                  list.get(i).send(str);116                }*/117                for( NewClient sc : list )118                    sc.send(str);119                } 120        }catch(EOFException e){121             //绑定异常,说明退出了122             System.out.println("该客户端退出了!");123         }catch (IOException e) {124             // TODO Auto-generated catch block125             e.printStackTrace();126         }finally{127               //当该线程消亡的时候,给予相应流的关闭128             try {129                  if(Dos!=null)Dos.close();130                  if(Dis!=null)Dis.close();131                  if(sc!=null)sc.close();132                 } catch (IOException e) {133                 // TODO Auto-generated catch block134                 e.printStackTrace();135             }136           }137   } 138 }139 }
View Code

 

线程练习题---简易多人聊天室