QQ丐版(韩顺平Java多用户通信项目)

客户端:

package Client;
import publi.*;
import publi.send_res;
import publi.user;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
// 客户端
public class Client_Sock {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Scanner scan = new Scanner(System.in);
        int count = 3;
        while (count>0){
        System.out.print("输入用户名:");
        String name1 = scan.next();
        System.out.print("输入密码:");
        String passwd = scan.next();
        try {
            int sock = Client_Sock.sock(name1, passwd);
            if (sock==-1){
                count--;
                System.out.println("错误,请重新输入");
            }
        }
       catch (java.lang.NullPointerException e){
       }
        }
        System.out.println("错误次数过多,客户端已退出");
    }
        //保证一个用户一个socket
   //用于用户登录验证
    public static int sock(String name, String pwd) throws IOException, ClassNotFoundException, InterruptedException {
        Socket socket = null;
        try {
            socket = new Socket(InetAddress.getByName("192.168.1.103"), 9999);
        }
        catch (java.net.ConnectException e){
            System.out.println("服务器未开启,请退出.......");
            System.exit(0);
        }
//        System.out.println("连接成功");
//        System.out.println("==================发送消息用于登录验证====================");
        OutputStream sock_out = socket.getOutputStream();
        ObjectOutputStream obj_out = new ObjectOutputStream(sock_out);
        obj_out.writeObject(new user(name, pwd));
        obj_out.flush();
//        System.out.println("==================接收消息====================");
        BufferedInputStream buf_in = new BufferedInputStream(socket.getInputStream());
        byte tmp[] = new byte[100];
        int lenth = buf_in.read(tmp);
        String str1 = new String(tmp, 0, lenth);
        if (!(str1.equals("登录失败"))) {
//            obj_out.close();  //关闭此流
//            buf_in.close();   //关闭此流
            String id = str1.split(":")[0]; //得到用户ID
            //用户自己的线程监听服务端发送的消息
            DateTimeFormatter str = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            HashMap<String, Client_run> map1 = new HashMap();
            Client_run Client_run = new Client_run(socket, "1");
            map1.put("1", Client_run);
            Client_run.start();
            Scanner scan = new Scanner(System.in);
            int count_mess = 0; //消息数
            int gc = 0;
            while (true){
                gc ++;
                LocalDateTime date_tmp = LocalDateTime.now();
                String date = str.format(date_tmp);
                System.out.println("\t" + "\t" + "欢 迎 用 户 " + name + "(" + id + ") 你 登 录 丐 版 QQ");
                System.out.println("\t" + "\t" + "\t" + "              1 : 显 示 在 线 用 户");
                System.out.println("\t" + "\t" + "\t" + "              3 : 私 发 消 息 ");
                System.out.println("\t" + "\t" + "\t" + "              5 : 发 送 文 件 ");
                System.out.println("\t" + "\t" + "\t" + "              6 : 离 开 系 统 ");
                System.out.println("\t" + "\t" + "\t" + "              7 : 群 发 消 息 ");
                String key = scan.next();
                if (key.equals("1")) {
                    byte[] bytes = "显示在线用户".getBytes();    //001表示显示用户
                    mess userlist = new mess("显示在线用户", "001", str1, date);
                    send_res.send(userlist, socket);
                    Thread.sleep(3000);
                } else if (key.equals("6")) {
                    byte[] bytes = "退出".getBytes();    //006表示退出系统
                    mess ask = new mess("退出", "006", str1, date);
                    send_res.send(ask, socket);
                    map1.clear();
                    System.out.println("退出............");
                    System.out.println("退出完成,bye");
                    System.exit(0);
                } else if (key.equals("3")) {  //私聊
                    byte[] bytes = "私聊".getBytes();    //003表示私聊
                    mess ask = new mess("私聊", "003", str1, date);
                    send_res.send(ask, socket);
                    Thread.sleep(1000); //休眠一秒,让服务器知道  (大可不必)
                    System.out.println("输 入 你 要 私 聊 用 户 ID");
                    String userid1 = scan.next();  //输入私聊用户ID
                    boolean loop = true;           //  可以添加切换用户 待做
                    while (loop) {
                        System.out.println("正 在 和 " + userid1 + " 私 聊 请 输 入 要 发 送 的 消 息(若 要 退 出 输 入 Q).......");
                        String text = scan.nextLine();  //输入私聊的内容
                        count_mess += 1;
                        if (text.equalsIgnoreCase("Q")) {
                            loop = false;
                            System.out.println("退 出 私 聊 界 面 成 功,你 共 发 送 了 " + count_mess + " 条 消 息");
                            count_mess = 0;
                        } else if (count_mess > 1) {
                            mess pri_mess = new mess(text, userid1, str1, date);
                            send_res.send(pri_mess, socket);
                            System.out.println("消息发送完成");
                            Thread.sleep(500); //让对方消息输出
                        }
                    }
                } else if (key.equals("7")) {  //群发
                    byte[] bytes = "群发".getBytes();    //007表示群发
                    mess ask = new mess("群发", "007", str1, date);
                    send_res.send(ask, socket);
                    Thread.sleep(500); //休眠一秒,让服务器知道  (大可不必)
                    boolean loop = true;
                    while (loop) {
                        System.out.println("正 在 群 聊 请 输 入 你 要 群 发 的 内 容 (若 要 退 出 输 入 Q)........");
                        String text = scan.nextLine();  //输入私聊的内容
                        if (text.equalsIgnoreCase("Q")) {
                            System.out.println("退 出 群 聊 界 面 成 功,你 共 发 送 了 " + count_mess + " 条 消 息");
                            count_mess = 0;
                            loop = false;
                        } else {
                            String userid = "00000"; //给服务器规定编号为00000 (和数据库里面的用户ID长度相同)
                            mess pri_mess = new mess(text, userid, str1, date);
                            send_res.send(pri_mess, socket);
                            count_mess++;
                        }
                    }
                } else if (key.equals("5")) {
                    int loop = 1;
                    while (loop >= 1) {
                        byte[] bytes = "发文件".getBytes();    //005表示发文件
                        mess ask = new mess("发文件", "005", str1, date);  //告诉服务器发送文件
                        send_res.send(ask, socket);
                        Thread.sleep(500); //休眠一秒,让服务器知道  (大可不必)
                        System.out.print("输 入 你 要 发 送 文 件 的 用 户 ID:");
                        String user111111 = scan.next();
                        System.out.print("输 入 文 件 路 径:");
                        String path = scan.next();
                        System.out.print("输 入 对 方 文 件 路 径:");
                        String path1 = scan.next();
                        // 从磁盘读取
                        FileInputStream file_read = new FileInputStream(path);
                        BufferedInputStream buff_read = new BufferedInputStream(file_read);
                        // 向外发送
                        OutputStream out_tmp = socket.getOutputStream();
                        BufferedOutputStream buff_write = new BufferedOutputStream(out_tmp);
                        byte tmp1[] = new byte[1024000];  //1 M
                        int read = 0;
                        ArrayList<byte[]> list = new ArrayList<>();
                        while ((read = buff_read.read(tmp1)) != -1) {
                            int i = 1;
                            byte reads[] = new byte[read];
                            System.arraycopy(tmp1, 0, reads, 0, read);
                            list.add(reads);
                            i++;
                            if (i % 10 == 0) {
                                System.gc();
                            }
                        }
                        buff_read.close();
                        file_read.close();
                        if (list.size() > 1000) {
                            // 规定文件不能大于1000M
                            System.out.println("文 件 过 大,不 能 发 送");
                        } else {
                            String file_leng = list.size() + " " + "客户端文件文件发送完毕路径为  "+path1;
                            mess file_ok = new mess(file_leng, user111111, str1, date);
                            send_res.send(file_ok, socket);
                            ObjectOutputStream obj_out1 = new ObjectOutputStream(socket.getOutputStream());
                            obj_out1.writeObject(list);
                            System.out.println("文 件 发 送 完 毕");
                            System.out.println("再 次 发 送 文 件 输 入 5,退 出 输 入 Q");
                            String file_double = scan.next();
                            if (file_double.equalsIgnoreCase("q")) {
                                System.out.println("共发送" + loop + "个文件");
                                loop = -1;
                                buff_read.close();
                                //  流未关闭
                                //  buf_in.close();
                            } else {
                                loop += 1;
                            }
                        }
                    }

                }
                if (gc%100==0){
                    System.gc();  //资源回收
                }
            }
        }
        else{
                socket.close();
                obj_out.close();
                buf_in.close();
                return -1;
            }
        }
    }

服务端:

package Serve;
import Tool.source;
import publi.mess;
import publi.run_th;
import publi.user;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Set;
import publi.*;
public class Serve_Sock {
    private static  Socket accept; //保证一个用户一个socket
    public static void sock() throws Exception {
//        LocalDateTime date_tmp = LocalDateTime.now();
//        DateTimeFormatter str = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String date = str.format(date_tmp);
        Calendar calendar = Calendar.getInstance();
        ServerSocket dk = new ServerSocket(9999);
        System.out.println("===========我是服务端,在端口9999监听,等待客户端连接================");
        while (true) {
             accept = dk.accept();   // 等待客户端连接,若一直没有连接,程序会被阻塞在这里
//            System.out.println("=========客户端连接成功,运行类型为:" + accept.getClass() + "==========");
//            System.out.println("=================开始接收消息判断用户名和密码是否正确===================");
            ObjectInputStream obj_in = new ObjectInputStream(accept.getInputStream());
            user user = (user) obj_in.readObject();
            String pwd = user.getPwd();
            String username = user.getUsername();
//            System.out.println("得到了用户输入的密码和用户名进行jdbc判断");
            int count = 0;
            Connection con = source.con();
            String sql = "select ID,name from user1 where name=? and pwd=MD5(?)";
            PreparedStatement sta = con.prepareStatement(sql);
            sta.setString(1, username);
            sta.setString(2, pwd);
            ArrayList result = source.sele(con, sta);
            if (result.size() != 0) {
//                System.out.println("登录成功"); //表示登录成功
                res o =(res) result.get(0);
                String id = o.getId();
                String sql1 = "update  user1 set login=now() where ID=?"; //更新数据库里面用户登录时间
                PreparedStatement sta1 = con.prepareStatement(sql1);
                sta1.setString(1, id);
                sta1.executeUpdate();
                //向客户端发送登录成功消息
                BufferedOutputStream buf_out = new BufferedOutputStream(accept.getOutputStream());
                id = id+":"+username;
                buf_out.write(id.getBytes());
                buf_out.flush();
//                buf_out.close(); //临时流关闭
//                obj_in.close(); //临时流关闭
                //System.out.println("=======发送成功=======");
                //开始启动线程
                run_th run = new run_th(accept, id);
                run.start();   //启动线程
                new mang_run(id ,run);
                //开始读取客户端发送过来的消息
                //推送消息
                HashMap<String, run_th> map = mang_run.getMap();
                LocalDateTime date_tmp = LocalDateTime.now();
                DateTimeFormatter str = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String date = str.format(date_tmp);
                Calendar cal1 = Calendar.getInstance();
                cal1.add(Calendar.MINUTE,-20);
                if (calendar.equals(cal1)){  // 消息20 分钟推送一次  (有误)
                    // 随机挑选一个推送
                    ArrayList<String> set =new ArrayList<>(map.keySet());
                    run_th run_th = map.get(set.get((int)(Math.random()*set.size())));
                    mess ms = new mess("1:东邪西毒南帝北丐中神通-2" +
                            ":Hello World-3:我从草原来-"+cal1,"00000","服务器",date);
                    run_th.send(ms);
                   System.gc();

                }
            }
            else {
                BufferedOutputStream buf_out = new BufferedOutputStream(accept.getOutputStream());
                buf_out.write("登录失败".getBytes());
                buf_out.flush();
                accept.close();
                buf_out.close();
            }
        }
    }
}

服务端的线程代码:

package publi;
import java.io.*;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

// 此类用来得到线程
public class run_th extends Thread {
    private Socket socket;
    private String userid;
    private  static  int  unline = 0;  //离线文件份数
    private static HashMap<String ,String> map_un = new HashMap();  // 标记离线文件

    public run_th(Socket socket, String userid) {
        this.socket = socket;
        this.userid = userid;
        //System.out.println("启动一个线程,线程ID为" + userid);
    }

    public void send(mess mess1) throws IOException, ClassNotFoundException {
        send_res.send(mess1, socket);
    }


    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    @Override
    public void run() {
        mess mess1 = null;
        int count = 0;
        int count1 = 0;  //用于判断用户私聊
        int count11 = 0; //用于判断用户群发
        int file = 0;    // 用于判断用户发文件
        boolean file_loop = true;
        while (true) {
            HashMap<String, run_th> map11 = mang_run.getMap();
            Set<String> set11 = map11.keySet();
            LocalDateTime date_tmp = LocalDateTime.now();
            DateTimeFormatter str1111 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String date = str1111.format(date_tmp);
            try {
                InputStream soct_in = socket.getInputStream();
                ObjectInputStream obj_in = new ObjectInputStream(soct_in);
                mess1 = (mess) obj_in.readObject();
                System.out.println("客户端的名称为:" + mess1.getName());
                //System.out.println("客户端要发送到的对象ID:" + mess1.getSendid());
                //System.out.println("客户端发送消息的时间:" + mess1.getDate());
                System.out.println("客户端发送消息的内容:" + mess1.getText());
                if (mess1 != null) {
                    count++;
                    System.out.println("记录消息的条数:"+count);
                }
                if (map_un.size()!=0&&set11.size()>=2){
                    System.out.println("存在离线文件");
                    Set<String> strings = map_un.keySet();
                    for (String i: strings){
//                        System.out.println("进入集合");
                        for (String j:set11){
                            if (j.indexOf(i)!=-1){
//                                System.out.println("===============");
                                // 从磁盘读取
                                String s = map_un.get(i).split("\\s+")[0];
                                String s1 = map_un.get(i).split("\\s+")[1].split(":")[1];
                                String s2 = map_un.get(i).split("\\s+")[2];
                                FileInputStream file_read = new FileInputStream(s);
                                BufferedInputStream buff_read = new BufferedInputStream(file_read);
                                // 向外发送
                                OutputStream out_tmp = socket.getOutputStream();
                                BufferedOutputStream buff_write = new BufferedOutputStream(out_tmp);
                                byte tmp1[] = new byte[1024000];  //1 M
                                int read = 0;
                                ArrayList<byte[]> list02 = new ArrayList<>();
                                while ((read = buff_read.read(tmp1)) != -1) {
                                    int i1 = 1;
                                    byte reads[] = new byte[read];
                                    System.arraycopy(tmp1, 0, reads, 0, read);
                                    list02.add(reads);
                                    i1++;
                                    if (i1% 10 == 0) {
                                        System.gc();
                                    }
                                }
                                String file_leng = list02.size() + "  " + "离线文件发送  "+s2;
                                mess file_ok = new mess(file_leng, "005", s1, date);
                                run_th run_th = map11.get(j);
//                                System.out.println("=======");
                                run_th.send(file_ok);
                                Socket socket111 = run_th.getSocket();
                                ObjectOutputStream obj_out1 = new ObjectOutputStream(socket111.getOutputStream());
                                obj_out1.writeObject(list02);
//                                System.out.println("离线文件发送完毕");
                                map_un.remove(i);
                                break;
                            }
                        }
                    }
                }

            } catch (Exception e) {
            } finally {
                if (mess1.getSendid().equals("001")) {   //得到在线用户
                    HashMap<String, run_th> map = mang_run.getMap();
                    Set<String> set = map.keySet();
                    StringBuffer str = new StringBuffer();
                    for (String i : set) {
                        str.append(i + "\t");   // 名称
                    }
                    try {
                        send_res.send(new mess(str.toString(), "001", "服务端", date), socket);
                    } catch (Exception e) {
                        //不处理
                    }
//                    System.out.println("ok");
                    count = 0;
                } else if (mess1.getSendid().equals("006")) {   //退出系统
                    HashMap<String, run_th> map = mang_run.getMap();
                    Set<String> set = map.keySet();
                    for (String i : set) {
                        int i1 = i.indexOf(mess1.getName());
                        if (i1 != -1) {
                            run_th run_th = map.get(i);
                            run_th.interrupt();
                            map.remove(i);
                            System.out.println("线程(用户)下线" + i);
                            break;
                        }
                    }
                    count = 0;
                } else if (mess1.getSendid().equals("003") || count1 == -1) {   //私聊
//                    System.out.println("收到用户想要私聊,over");
                    count1 = -1;
                    boolean loop = false;  //控制阀
                    if (count >= 2) {
                        loop = true;
                    }
                    while (loop) {
                        if (mess1.getText().equalsIgnoreCase("q")) {
                            loop = false;
                            count = 0;
                            count1 = 0;
                            System.out.println("客户端退出");
                        } else {
                            HashMap<String, run_th> map = mang_run.getMap();
                            Set<String> set = map.keySet();
                            int logo = 1;
                            for (String i : set) {
                                int i1 = i.indexOf(mess1.getSendid());
                                if (i1 != -1) {
                                    mess pri_mess = new mess(mess1.getText(), "003", mess1.getName(), date);
                                    run_th run_th = map.get(i);
                                    System.out.println(i1);
                                    try {
                                        run_th.send(pri_mess);
                                        System.out.println(mess1.getName() + "发送消息给" + mess1.getSendid());
                                    } catch (Exception e) {
                                    } //不处理
                                    logo = 0;
                                    loop = false;
                                }
                            }
                            if (logo != 0) {
                                System.out.println("当前用户不在线");
                                try {
                                    send_res.send(new mess("当前用户不在线".toString(), "003&-1", mess1.getSendid(), date), socket);
                                } catch (IOException e) {
                                    //不处理
                                } catch (ClassNotFoundException e) {
                                    //不处理
                                }
                                loop = false;
                            }
                        }
                    }
                } else if (mess1.getSendid().equals("007") || count11 == -1) {   //私聊
//                    System.out.println("收到用户想要群发,over");
                    count11 = -1;
                    boolean loop = false;  //控制阀
                    if (count >= 2) {
                        loop = true;
                    }
                    while (loop) {
                        if (mess1.getText().equalsIgnoreCase("q")) {
                            loop = false;
                            count = 0;
                            count11 = 0;
                            System.out.println("客户端退出");
                        } else {
                            HashMap<String, run_th> map = mang_run.getMap();
                            Set<String> set = map.keySet();
                            int logo = 1;
                            for (String i : set) {
                                if (i.indexOf(mess1.getName()) == 0) {
                                    continue;
                                } else {
                                    mess pri_mess = new mess(mess1.getText(), "007", mess1.getName(), date);
                                    run_th run_th = map.get(i);
                                    try {
                                        run_th.send(pri_mess);
                                        System.out.println(mess1.getName() + "发送消息到" + i + "内容为:" + mess1.getText());
                                    } catch (Exception e) {
                                    } //不处理
                                }
                                loop = false;
                            }
                        }
                    }
                } else if ((mess1.getSendid().equals("005")) || (file == 1)) {   //用户发文件
                    file = 1;
                    int line = 0;
                    if (count == 2) {
                        //count == 2 说明用户开始发送文件
                        String length = mess1.getText().split("\\s+")[0]; //得到文件长度
                        String path = mess1.getText().split("\\s+")[2]; //得到文件长度
                        ArrayList<byte[]> list = new ArrayList();
                        //开始读取
                        try {
                            ObjectInputStream obj_in = new ObjectInputStream(socket.getInputStream());
                            ArrayList<byte[]> list1 = (ArrayList) obj_in.readObject();
                            HashMap<String, run_th> map = mang_run.getMap();  //用户线程
                            Set<String> set = map.keySet();
                            for (int i = 0; i < Integer.parseInt(length); i++) {
                                byte[] bytes1 = list1.get(i);
                                list.add(bytes1);
                                System.out.println("得到文件长度为:" + bytes1.length);
                            }
                            for (String i1 : set) {
                                int i11 = i1.indexOf(mess1.getSendid());
                                if (i11 != -1) {
                                    String file_leng = list.size() + "  " + "文件发送  "+path;
                                    mess file_ok = new mess(file_leng, "005", mess1.getName(), date);
                                    run_th run_th = map.get(i1);
                                    run_th.send(file_ok);
                                    Socket socket111 = run_th.getSocket();
                                    ObjectOutputStream obj_out1 = new ObjectOutputStream(socket111.getOutputStream());
                                    obj_out1.writeObject(list);
                                    System.out.println("文件发送完毕!!!");
                                    line = 1;
                                    }
                                    file = 0;
                                    count = 0;
                                }
                            if (line ==0){
                                System.out.println("当前用户不在线");
                                String path1 = "";
                                String[] split = path.split("\\.");
                                String format = split[split.length-1];
                                if (format.equals("mp4")){
                                    path1 = "d:\\video"+unline+"."+format;
                                    unline++;
                                } else if (format.equals("mp3")) {
                                    path1 = "d:\\music"+unline+"."+format;
                                    unline++;
                                }
                                else {
                                    path1 = "d:\\image"+unline+"."+format;
                                    unline++;
                                }
                                System.out.println(path1);
                                FileOutputStream file_out = new FileOutputStream(path1);
                                BufferedOutputStream buff_file = new BufferedOutputStream(file_out);
                                for (byte[] i:list){
                                    buff_file.write(i);
                                }
                                map_un.put(mess1.getSendid(),path1+"  "+mess1.getName()+"  "+path);
                                System.out.println("文件写出完成");
                            }
                            } catch (Exception e) {
                        }
                    }
                        }
            }
            System.gc();

            }
        }
    }
德鲁利连接池:
package Tool;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import publi.res;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Properties;
public class source {
    public source() {
        System.out.println("无参构造方法");
    }
    public static  Connection con() throws Exception {
        Connection con = null;
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream("src\\Tool\\druid.properties"));
            DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
            con = dataSource.getConnection();

        }
        catch (Exception e){
            System.out.println(e);
        }
            return con;
    }
    public static  void close(Connection con, PreparedStatement sta) throws Exception {
        con.close();
        sta.close();
    }
    public static  void close(Connection con, PreparedStatement sta,ResultSet set) throws Exception {
        //System.out.println("没有关闭con");
        sta.close();
        set.close();
    }
    public static  ArrayList sele(Connection con,PreparedStatement sta) throws Exception {
        ResultSet result = sta.executeQuery();
        ArrayList list = new ArrayList();
        while (result.next()){
            list.add(new res(result.getString("ID"),result.getString("name")));
        }
        close(con,sta,result);
       return list;
    }
}
客户端线程代码:
package Client;
import publi.mang_run;
import publi.mess;
import publi.send_res;

import java.io.*;
import java.net.Socket;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

// 此类用来得到线程
public class Client_run extends Thread{
    private Socket socket;
    private String  userid;
    public Client_run(Socket socket,String useid){
        this.socket = socket;
        this.userid = useid;
        //System.out.println("启动一个线程,线程ID为"+useid);
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    @Override
    public void run() {
//        LocalDateTime date_tmp = LocalDateTime.now();
//        DateTimeFormatter str1111 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String date  = str1111.format(date_tmp);
        StringBuffer name =new StringBuffer("");
        StringBuffer id =new StringBuffer("");
        StringBuffer send_date =new StringBuffer("");
        StringBuffer text =new StringBuffer("");
        while (true) {
            try {
                // 接收消息
                InputStream soct_in = socket.getInputStream();
                ObjectInputStream obj_in = new ObjectInputStream(soct_in);
                mess mess1 = (mess) obj_in.readObject();
                name.append(mess1.getName());
                id.append(mess1.getSendid()) ;
                send_date.append(mess1.getDate()) ;
                text.append(mess1.getText());
                if (id.toString().equals("001")){
                    System.out.println("===============当前在线用户列表  "+send_date.toString().split("\\s+")[1]+"==============");
                    String[] data = text.toString().split("\\s+");
                    int tmp = 0;
                    for (int i =0;i<data.length;i++){
                        String split = data[i].split(":")[0];
                        String split1 = data[i].split(":")[1];  //用户
                        tmp = i+1;
                        System.out.println("\t"+"    用户 "+tmp+" : "+split1+" ("+split+")");
                        tmp = 0;
                    }
                }
                else if (id.toString().equals("003")){
                    System.out.println("收到一条来自用户"+name.toString().split(":")[1]+"的消息:"+text.toString());
                } else if (id.toString().equals("003&-1")) {
                    System.out.println("当前用户"+name+"未上线");  //实现离线发送
                } else if (id.toString().equals("007")) {  //群发
                    System.out.println("收到一条来自用户"+name+"群发的消息:"+text.toString());
                } else if (id.toString().equals("005")) {
                    System.out.println("收到一个来自用户"+name+"发送的文件");
                    String path = text.toString().split("\\s+")[2];  //得到文件地址
                    while (true) {
                        try {
                            ObjectInputStream obj_i111n = new ObjectInputStream(socket.getInputStream());
                            ArrayList<byte[]> list1 = (ArrayList) obj_i111n.readObject();
                            if (list1.size() != 0) {
                                FileOutputStream file_out = new FileOutputStream(path);
                                BufferedOutputStream buff_file = new BufferedOutputStream(file_out);
                                for (byte[] i : list1) {
                                    buff_file.write(i);
                                }
                                buff_file.close();
                                file_out.close();
                                System.out.println("文件保存在"+path);
                            }
                        } catch (Exception e) {}
                        break;
                    }
                }
            }
            catch (Exception e){}
            finally {
                //清空
               name.setLength(0);
               id.setLength(0);
               send_date.setLength(0);
               text.setLength(0);
            }
        }
    }
}
线程管理类:
package publi;
import Client.Client_run;

import java.util.HashMap;
// 此类用来管理线程
public class mang_run {
    private String id;

    public static HashMap<String, run_th> getMap() {
        return map;
    }

    public static void setMap(HashMap<String, run_th> map) {
        mang_run.map = map;
    }

    private run_th run;

    private static HashMap<String ,run_th> map = new HashMap();

    public mang_run(String id, run_th run) {
        this.id = id;
        this.run = run;
        map.put(id, run);
        System.out.println("加入一个线程(服务端),ID为:"+id);
    }
//    public static void user(String id, Client_run run) {
//        map1.put(id,run);
//        System.out.println("客户端加入一个线程,ID为:"+id);
//    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public run_th getRun() {
        return run;
    }

    public void setRun(run_th run) {
        this.run = run;
    }
}
发消息类:
package publi;
import java.io.*;
import java.net.Socket;
public class send_res {
    public static void send(mess me, Socket socket1) throws IOException, ClassNotFoundException {
        OutputStream sock_out = socket1.getOutputStream();
        ObjectOutputStream obj_out = new ObjectOutputStream(sock_out);
        obj_out.writeObject(me);
        obj_out.flush();
//        System.out.println("==================发送消息完成====================");
    }
    public static void res(Socket socket1) throws IOException, ClassNotFoundException {
        System.out.println("==================接收消息====================");
        ObjectInputStream obj_in = new ObjectInputStream(socket1.getInputStream());
        mess mess1 = (mess) obj_in.readObject();
        System.out.println("客户端的名称为:"+mess1.getName());
        System.out.println("客户端要发送到的对象ID:"+mess1.getSendid());
        System.out.println("客户端发送消息的时间:"+mess1.getDate());
        System.out.println("客户端发送消息的内容:"+mess1.getText());
    }
    public static void send_file(Socket socket1,String id) throws IOException, ClassNotFoundException {
        System.out.println("==================发送文件====================");
        OutputStream out_tmp = socket1.getOutputStream();
        BufferedOutputStream buff_write = new BufferedOutputStream(out_tmp);
    }
    }
消息类:
package publi;

import java.io.Serializable;

public class mess implements Serializable {
    private String text;   //发送的文本
    private String sendid; //要发送的用户ID
    private String name; // 发送者
    private String date; // 发送时间

    public mess(String text, String sendid, String name, String date) {
        this.text = text;
        this.sendid = sendid;
        this.name = name;
        this.date = date;
    }
    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getSendid() {
        return sendid;
    }

    public void setSendid(String sendid) {
        this.sendid = sendid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

}
用户类:
package publi;

import java.io.Serializable;

public class user implements Serializable {
    private  String username;
    private String pwd;

    public user(String username, String pwd) {
        this.username = username;
        this.pwd = pwd;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}
结构

演示:

 

 

数据库表的结构:

pwd进行了md5加密 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值