A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

今天在学socket,写了一个简单聊天室的代码实现服务器的广播
首先是一个ServerSocket启动类
  1. package com.mycode.server;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;

复制代码
然后就是一个线程处理类ClientThread
  1. package com.mycode.server;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.net.Socket;
  7. public class ClientThread implements Runnable {
  8. private Socket socket = null;
  9. private ChatRoom chatroom = null;
  10. private BufferedReader br = null;
  11. private PrintWriter pw = null;
  12. private String name = "";
  13. public String getName() {
  14. return name;
  15.     }
  16. public Socket getSocket() {
  17. return socket;
  18.     }
  19. /***
  20.      * 构造一个客户端线程获得服务器的socket以及当前的Chatroom对象
  21.      *
  22.      * @param socket
  23.      *            服务器的socket
  24.      * @param chatroom
  25.      *            当前的Chatroom
  26.      */
  27.     public ClientThread(Socket socket, ChatRoom chatroom) {
  28. this.socket = socket;
  29.         this.chatroom = chatroom;
  30.         this.name = socket.getInetAddress().getHostName();

  31.         try {
  32.             br = new BufferedReader(new InputStreamReader(socket
  33.                     .getInputStream()));
  34.             pw = new PrintWriter(socket.getOutputStream());
  35. chatroom.in(this);
  36.         } catch (IOException e) {
  37.             System.out.println(e.getMessage());
  38.         }
  39. }
  40. /***
  41.      * 说。。。
  42.      * @param content 内容
  43.      * */
  44.     public void clientSay(String content) {
  45. pw.println(content);
  46.         pw.flush();
  47.     }

  48.     long lastTime = 0;
  49.     int count=0;
  50.     @Override
  51.     public void run() {
  52. try {
  53.             while (true) {
  54. String readLine = br.readLine();
  55.                 if (System.currentTimeMillis() - lastTime < 3000) {
  56.                     clientSay("兄弟禁言1分钟--测试3秒");
  57.                     count++;
  58.                 } else {
  59.                     chatroom.say(this.name, readLine);
  60.                 }
  61.                 lastTime = System.currentTimeMillis();
  62. if(count>=3)
  63.                 {
  64.                     chatroom.say("系统提示"+this.name, "恶意刷屏,ByeBye!");
  65.                    br.close();
  66.                    //socket.close();
  67.                 }
  68.                 if (readLine.equals("exit")) {
  69.                     br.close();
  70.                 }
  71. }
  72.         } catch (Exception e) {
  73.             chatroom.out(this);
  74.             pw.close();
  75.         }
  76.     }
  77. }
复制代码
最后就是个ChatRoom类作为聊天室的场地,服务器就搭建完毕咯
  1. package com.mycode.server;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class ChatRoom {
  5. List<ClientThread> clients = new ArrayList<ClientThread>();//存储进入聊天室的客户端
  6. String msg = "";
  7. /***
  8.      * 进入聊天室提示信息
  9.      * * @param clientThread  获得一个客户端对象
  10.      **/
  11.     public void in(ClientThread clientThread) {
  12. boolean add = clients.add(clientThread);
  13.         if (add) {
  14.             msg = clientThread.getName() + "进入聊天室!";
  15.             NoteALL(msg);
  16.             if (clients.size() > 0) {
  17.                 System.out.println("当前在线:"+clients.size()+"人");
  18.                 showAllClient();
  19.             }
  20. }
  21.     }
  22. public void out(ClientThread ct) {
  23. boolean remove = clients.remove(ct);
  24.         if (remove) {
  25.             msg = ct.getName() + "退出聊天室!";
  26.             NoteALL(msg);
  27.             if (clients.size() > 0) {
  28.                 System.out.println("当前在线:"+clients.size()+"人");
  29.                 showAllClient();
  30.             }
  31.         }
  32.     }
  33. private void showAllClient() {
  34. for (ClientThread clientThread : clients) {
  35.             System.out.println(clientThread.getName());
  36.         }
  37. }
  38. private synchronized void NoteALL(String msg) {
  39. for (ClientThread clientThread : clients) {
  40.             clientThread.clientSay(msg);
  41.         }
  42.         System.out.println(msg);
  43. }
  44. public synchronized void say(String name, String content) {
  45. msg = name + " Say:" + content;
  46.         NoteALL(msg);
  47. }
  48. }
复制代码
启动MainFrame开启服务器。服务端搞定下面就是客户端了
  1. package com.mycode.client;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.net.Socket;
  7. import java.net.UnknownHostException;
  8. import java.util.Scanner;
  9. /***
  10. * 客户端
  11. * * @author backin
  12. * */
  13. public class Client {
  14. static PrintWriter pw = null;
  15. static BufferedReader br = null;
  16. static Scanner input = new Scanner(System.in);
  17. public static void main(String[] args) {
  18. String IPADDRESS = "127.0.0.1";
  19.         int PORT = 9990;
  20. try {
  21. Socket socket = new Socket(IPADDRESS, PORT);
  22. pw = new PrintWriter(socket.getOutputStream());
  23.             br = new BufferedReader(new InputStreamReader(socket
  24.                     .getInputStream()));
  25. System.out.print(socket.getLocalPort());//获取当前与服务器通信的端口,非连接端口
  26. new Thread() {
  27. public void run() {//输入到程序端线程,避免影响主线程
  28. try {
  29.                         System.out.println(br.readLine());
  30.                     } catch (IOException e) {
  31. System.out.println("Server is missing...");
  32.                         return;
  33.                     }
  34.                 };
  35.             }.start();
  36.             new Thread() {//输出到服务器线程避免影响主线程
  37. public void run() {
  38. while (true) {
  39.                         String str = input.next();
  40.                         pw.println(str);
  41.                         pw.flush();
  42.                         if (str.equals("exit")) {
  43.                             pw.close();
  44.                         }
  45.                     }
  46.                 }
  47. }.start();
  48. } catch (UnknownHostException e) {
  49.             System.out.println("Server is not found!"+e.getMessage());
  50.         } catch (IOException e) {
  51.             System.out.println("IO error!"+e.getMessage());
  52.         }
  53.     }
  54. }
复制代码
OK程序有点ugly,大伙来帮忙完善下,交流交流


3 个回复

倒序浏览
有板凳自己做,格式怎么个这样子,哎真心很...
回复 使用道具 举报
你可以写成图形界面  弄个客户端和服务器端相互发信息相信会有趣很多
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马