TCP的多人聊天室

TCP的多人聊天室

上次写了一个只能两个人通信的TCP,这次写了个可以多人聊天的,利用多线程实现。

设计模式:

服务端:首先运行服务器,然后启动一个专门处理客户端消息的线程,然后监听是否有客户端连接,如果有人连接就单独为这个客户端开辟一个线程来处理。有多少人就开辟几个线程,并把客户端的消息放到消息集合里面,并把这些消息发送给出自己之外的其他所有人。

客户端:连接服务器后就会发送一条消息给服务器告诉服务器我已经连上来了,并开启一个线程专门接收服务器发送的信息。

服务端代码:

[html]  view plain  copy
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStreamReader;  
  4. import java.io.PrintWriter;  
  5. import java.net.ServerSocket;  
  6. import java.net.Socket;  
  7. import java.util.ArrayList;  
  8. import java.util.LinkedList;  
  9. import java.util.List;  
  10.   
  11. /**  
  12.  *   
  13.  * @Description 多人聊天服务器  
  14.  * @author Bush罗  
  15.  * @date 2018年4月3日  
  16.  *  
  17.  */  
  18. public class Server extends ServerSocket {  
  19.   
  20.     private static final int SERVER_PORT = 5566;  
  21.     private static boolean isPrint = false;// 是否输出消息标志  
  22.     private static List<String> user_list = new ArrayList<String>();// 登录用户集合  
  23.     private static List<ServerThread> thread_list = new ArrayList<ServerThread>();// 服务器已启用线程集合  
  24.     private static LinkedList<Message> message_list = new LinkedList<Message>();// 存放用户消息的队列  
  25.   
  26.     /**  
  27.      * 创建服务端Socket,创建向客户端发送消息线程,监听客户端请求并处理  
  28.      */  
  29.     public Server() throws IOException {  
  30.         super(SERVER_PORT);// 创建ServerSocket  
  31.         new PrintOutThread();// 处理所有客户端发送的消息  
  32.         System.out.println("服务器已启动");  
  33.         try {  
  34.             while (true) {// 监听客户端请求,启个线程处理  
  35.                 Socket socket = accept();  
  36.                 new ServerThread(socket);  
  37.             }  
  38.         } catch (Exception e) {  
  39.         } finally {  
  40.             close();  
  41.         }  
  42.     }  
  43.   
  44.     /**  
  45.      * 监听是否有消息在队列里的线程类,向除自己之外的客户端发送消息  
  46.      */  
  47.   
  48.     class PrintOutThread extends Thread {  
  49.   
  50.         public PrintOutThread() {  
  51.             start();  
  52.         }  
  53.   
  54.         @Override  
  55.         public void run() {  
  56.             while (true) {  
  57.                 //如果消息队列没有消息则暂停当前线程,把cpu片段让出给其他线程,提高性能  
  58.                 if (!isPrint) {  
  59.                     try {  
  60.                         Thread.sleep(500);  
  61.                         sleep(100);  
  62.                     } catch (InterruptedException e) {  
  63.                         // TODO Auto-generated catch block  
  64.                         e.printStackTrace();  
  65.                     }  
  66.                     continue;  
  67.                 }  
  68.                 // 将缓存在队列中的消息按顺序发送到各客户端,并从队列中清除。  
  69.                 Message message = (Message) message_list.getFirst();  
  70.                 // 对所有的用户的线程遍历,如果不是自己发的消息就广播给其他人  
  71.                 for (int i = 0; i < thread_list.size(); i++) {  
  72.                     // 由于添加线程和用户是一起的,所以i所对应的用户就是i所对应的线程,可以根据这个判断是不是自己的线程  
  73.                     ServerThread thread = thread_list.get(i);  
  74.                     if (message.getName() != user_list.get(i)) {  
  75.                         thread.sendMessage(message);  
  76.                     }  
  77.                 }  
  78.                 message_list.removeFirst();  
  79.                 isPrint = message_list.size() > 0 ? true : false;  
  80.                   
  81.             }  
  82.         }  
  83.     }  
  84.   
  85.     /**  
  86.      * 服务器线程类  
  87.      */  
  88.     class ServerThread extends Thread {  
  89.         // 客户端  
  90.         private Socket client;  
  91.         // 打印流  
  92.         private PrintWriter out;  
  93.         // 读取客户端发的消息的缓冲流  
  94.         private BufferedReader in;  
  95.         // 客户名字  
  96.         private String name;  
  97.   
  98.         public ServerThread(Socket s) throws IOException {  
  99.             client = s;  
  100.             out = new PrintWriter(client.getOutputStream(), true);  
  101.             in = new BufferedReader(new InputStreamReader(  
  102.                     client.getInputStream()));  
  103.             in.readLine();  
  104.   
  105.             start();  
  106.         }  
  107.   
  108.         @Override  
  109.         public void run() {  
  110.             out.println("成功连上聊天室,请输入你的名字:");  
  111.             System.out.println(getName());  
  112.             try {  
  113.                 int flag = 0;  
  114.                 String line = in.readLine();  
  115.                 while (!"byeClient".equals(line)) {  
  116.   
  117.                     // 查看在线用户列表  
  118.                     if ("showuser".equals(line)) {  
  119.                         out.println(this.listOnlineUsers());  
  120.                         line = in.readLine();  
  121.                     }  
  122.                     if ("showmessage".equals(line)) {  
  123.                         out.println(this.listmassage());  
  124.                         line = in.readLine();  
  125.                     }  
  126.   
  127.                     // 第一次进入,保存名字  
  128.                     if (flag == 0) {  
  129.                         name = line;  
  130.                         user_list.add(name);  
  131.                         thread_list.add(this);  
  132.                         out.println(name + "你好,可以开始聊天了...");  
  133.                         System.out.println(name + "连接服务器");  
  134.                         pushMessage(name, "进入聊天室");  
  135.                     } else {  
  136.                         pushMessage(name, line);  
  137.                     }  
  138.                     flag++;  
  139.                     line = in.readLine();  
  140.                     System.out.println(name + ":" + line);  
  141.                 }  
  142.                 out.println("byeClient");  
  143.             } catch (Exception e) {  
  144.                 e.printStackTrace();  
  145.             } finally {// 用户退出聊天室  
  146.                 try {  
  147.                     client.close();  
  148.                 } catch (IOException e) {  
  149.                     e.printStackTrace();  
  150.                 }  
  151.                 thread_list.remove(this);  
  152.                 user_list.remove(name);  
  153.                 pushMessage(name, "退出了聊天室");  
  154.             }  
  155.         }  
  156.   
  157.         // 放入消息队列末尾,准备发送给客户端  
  158.         public void pushMessage(String name, String msg) {  
  159.             Message message = new Message(name, msg);  
  160.             // 放入用户信息  
  161.             message_list.addLast(message);  
  162.             // 表示可以向其他用户发送消息  
  163.             isPrint = true;  
  164.         }  
  165.   
  166.         // 向客户端发送一条消息  
  167.         public void sendMessage(Message message) {  
  168.             out.println(message.getName() + ":" + message.getMessage());  
  169.         }  
  170.   
  171.         // 统计在线用户列表  
  172.         private String listOnlineUsers() {  
  173.             String s = "--- 在线用户列表 ---\015\012";  
  174.             for (int i = 0; i < user_list.size(); i++) {  
  175.                 s += "[" + user_list.get(i) + "]\015\012";  
  176.             }  
  177.             s += "--------------------";  
  178.             return s;  
  179.         }  
  180.   
  181.         // 统计在线用户列表  
  182.         private String listmassage() {  
  183.             String s = "--- 消息列表 ---\015\012";  
  184.             for (int i = 0; i < message_list.size(); i++) {  
  185.                 s += "[" + message_list.get(i) + "]\015\012";  
  186.             }  
  187.             s += "--------------------";  
  188.             return s;  
  189.         }  
  190.     }  
  191.   
  192.     public static void main(String[] args) throws IOException {  
  193.         new Server();// 启动服务端  
  194.     }  
  195. }  
  196.   
  197. // 消息类,用户以及用户发的一条消息  
  198. class Message {  
  199.     // 用户名  
  200.     String client;  
  201.     // 消息  
  202.     String message;  
  203.   
  204.     public Message() {  
  205.         super();  
  206.         // TODO Auto-generated constructor stub  
  207.     }  
  208.   
  209.     public Message(String client, String message) {  
  210.         super();  
  211.         this.client = client;  
  212.         this.message = message;  
  213.     }  
  214.   
  215.     public String getName() {  
  216.         return client;  
  217.     }  
  218.   
  219.     public void setName(String name) {  
  220.         this.client = name;  
  221.     }  
  222.   
  223.     public String getMessage() {  
  224.         return message;  
  225.     }  
  226.   
  227.     public void setMessage(String message) {  
  228.         this.message = message;  
  229.     }  
  230.   
  231.     @Override  
  232.     public String toString() {  
  233.         return "Message [client=" + client + "message=" + message + "]";  
  234.     }  
  235.   
  236. }  

客户端代码:

[html]  view plain  copy
  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3. import java.io.PrintWriter;  
  4. import java.net.Socket;  
  5.   
  6. /**  
  7.  *   
  8.  * @Description 多人聊天客户端  
  9.  * @author Bush罗  
  10.  * @date 2018年4月3日  
  11.  *  
  12.  */  
  13. public class SocketClient extends Socket{  
  14.   
  15.     private static final String SERVER_IP = "127.0.0.1";  
  16.     private static final int SERVER_PORT = 5566;  
  17.       
  18.     private Socket client;  
  19.     private PrintWriter out;  
  20.     private BufferedReader in;  
  21.       
  22.     /**  
  23.      * 与服务器连接,并输入发送消息  
  24.      */  
  25.     public SocketClient() throws Exception{  
  26.         super(SERVER_IP, SERVER_PORT);  
  27.         client = this;  
  28.         out = new PrintWriter(this.getOutputStream(), true);  
  29.         in = new BufferedReader(new InputStreamReader(this.getInputStream()));  
  30.         new readLineThread();  
  31.         out.println("我已经连接服务器");  
  32.         while(true){  
  33.             in = new BufferedReader(new InputStreamReader(System.in));  
  34.             String input = in.readLine();  
  35.             out.println(input);  
  36.         }  
  37.     }  
  38.       
  39.     /**  
  40.      * 用于监听服务器端向客户端发送消息线程类  
  41.      */  
  42.     class readLineThread extends Thread{  
  43.           
  44.         private BufferedReader buff;  
  45.         public readLineThread(){  
  46.             try {  
  47.                 buff = new BufferedReader(new InputStreamReader(client.getInputStream()));  
  48.                 start();  
  49.             } catch (Exception e) {  
  50.             }  
  51.         }  
  52.           
  53.         @Override  
  54.         public void run() {  
  55.             try {  
  56.                 while(true){  
  57.                     String result = buff.readLine();  
  58.                     if("byeClient".equals(result)){//客户端申请退出,服务端返回确认退出  
  59.                         break;  
  60.                     }else{//输出服务端发送消息  
  61.                         System.out.println(result);  
  62.                     }  
  63.                 }  
  64.                 in.close();  
  65.                 out.close();  
  66.                 client.close();  
  67.             } catch (Exception e) {  
  68.             }  
  69.         }  
  70.     }  
  71.       
  72.     public static void main(String[] args) {  
  73.         try {  
  74.             new SocketClient();//启动客户端  
  75.         } catch (Exception e) {  
  76.         }  
  77.     }  
  78. }  

效果图:开了一个服务器连个客户端:

我的编码格式是utf-8的


原文章地址:https://blog.csdn.net/bushqiang/article/details/79822349

猜你喜欢

转载自blog.csdn.net/sliver1836/article/details/80183386