用java实现简易的聊天室

实现一个Java版即时聊天程序。

【功能提示:可选择部分功能实现(至少5个功能),可增加功能】

1、用户登录及登录验证:用户能够使用固定帐号(帐号程序内置即可,无需完成额外的注册功能)登录系统,系统能对预定的帐号、密码进行验证。 

2、两两聊天功能。 

3、建群及群聊功能,并且在下次登录时,群聊组依然存在。

4、共享白板:聊天时,可创建白板,在白板上共同绘制图形,可保存白板绘制的图片。

5、好友管理:能够显示好友列表,并能够添加、修改、删除好友。

6、在线、离线状态显示:能够显示好友的在线状态或离线状态。 

7、聊天记录管理:能够以文件或数据库形式将聊天记录进行存储,并能打开、显示、删除所存储的聊天记录。

需求分析

这个系统准备做的是一个即时聊天程序,首先要有用户,因此要创建一个用户类,最简单的用户类也要包括账号,密码,在线状态,朋友和群聊这五个部分,对于用户登录及登录验证,我们要对用户输入的账号密码和程序内置的账号及其密码进行对比用于登录,这里面需要多线程才能提供不同的用户登录,需要开发服务端和客户端,也需要文件来记录用户的登录状态,以及用户的朋友和所属群聊。服务端方面要提供多个线程来处理不同用户,并且记录在线的用户用于发消息,也需要开发一个线程来接收客户端发来的消息用于转发;客户端方面也是需要提供发消息和收消息的线程。

即时聊天系统的设计

1. 系统的总体设计    

系统总体需要一个用户类用以区分不同的用户,需要一个客户端类用以发消息,需要一个客户端线程用以读取消息,需要一个服务端类用以接收上线的客户端,需要一个服务端线程用以给在线的客户端发消息,需要一个操作类用于用户的登录以及后面的操作。

2. 系统的设计

一.类的设计:

用户类(user):里面包括用户的账号,密码,在线状态,朋友,群聊,并且要提供有参构造器用以程序内置账号,还需要提供get和set方法用以修改或获得在线状态,朋友和群聊

数据结构:

 private String account; 

private String password;

private ArrayList<Friend> friends; 
 private ArrayList<String> group;

private boolean state; 
 
 服务端读取信息类(ServerReaderThread):里面包括对在线用户的socket的添加删除操作,而且还需要根据客户端传来的信息区分当前聊天是群聊还是一对一聊天,思路基本一致,首先判断自己是谁,socket是什么,然后在onlines中找到对应的socket,然后通过输入输出流将信息发送给对方。
    数据结构:
 private Socket socket;

private String username//自己的用户名

private String friendUsername//私聊的用户名

private int info;   //判断是群聊还是私聊
 
 服务端类(Server):在服务端方面要保存客户端在线的socket以便通过服务端去收发消息,还需要userList去保存已经内置好的账号的相关信息,并且还需要创建文件来保存用户的在线状态,朋友,以及群聊,防止线程安全问题。
    数据结构:
public static Map<Socket,String> onlines = new HashMap<>();

public static ArrayList<user> userList = new ArrayList<>();

public static ArrayList<Friend> firendList = new ArrayList<>();

public static File file = new File("userData.txt");
二.对象的协作过程:
        对象的协作过程主要集中在客户端的操作界面上,在用户的登录及其登录后的相关操作都保存在MainThread类,并且需要去继承线程,因为有多个用户,在进行登录的时候会需要使Server中的userList进行判断正确与否;在进行添加好友,删除好友,显示好友的状态以及建立群聊等时候需要用到文件,涉及到文件的读取及写入;在进行一对一聊天或者群聊的时候都需要Client,
ClientReaderThread,Server,ServerReaderThread多个类,其中Client用以发消息,ClientReaderThread用以收取别人发来的消息,Server用以收取从客户端发来的消息并且记录在线的客户端的相关信息,ServerReaderThread用以将客户端发来的消息进行转发。

3.3 数据库的设计或文件结构的设计

文件的结构设计:保存用户的相关信息的文件为userData.txt当写入文件的时候,一个用户的信息占据一行,因此在读取数据的时候可以按行读取,易于区分,在一行中,用逗号分隔开用户的状态,朋友及其群聊,在朋友中用‘-‘区分多个朋友,在群聊中用’#‘进行区分多个群聊

4 即时聊天系统的实现

·4.1项目结构及配置

(1)用户类(user):里面包括用户的账号,密码,在线状态,朋友,群聊,并且要提供有参构造器用以程序内置账号,还需要提供get和set方法用以修改或获得在线状态,朋友和群聊

(2)服务端读取信息类(ServerReaderThread):里面包括对在线用户的socket的添加删除操作,而且还需要根据客户端传来的信息区分当前聊天是群聊还是一对一聊天,思路基本一致,首先判断自己是谁,socket是什么,然后在onlines中找到对应的socket,然后通过输入输出流将信息发送给对方。
(3)服务端类(Server):在服务端方面要保存客户端在线的socket以便通过服务端去收发消息,还需要userList去保存已经内置好的账号的相关信息,并且还需要创建文件来保存用户的在线状态,朋友,以及群聊,防止线程安全问题,这个也是服务端开启的类。
(4)操作界面类(MainThread):包括用户的登录界面,登录成功后的操作界面以及对应的操作数,以及各种操作所对应的具体的代码实现。
(5)客户端类(Client):包括用户发消息给服务端的具体实现代码,以及开启客户端读取信息的线程。
(6)客户端读取信息类(ClientReaderThread):包括收取从服务端发来的消息的具体实现代码。
(7)客户端开启类(ThreadStart):包含多线程,用以区分不同用户,这是客户端开启的类

代码:

client类 

import jdk.swing.interop.SwingInterOpUtils;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void ClientMain(String username,String friendUsername,int info) throws Exception {
        Socket socket = new Socket(InetAddress.getLocalHost(),8888);
        new ClientReaderThread(socket).start();
        Scanner sc = new Scanner(System.in);
        OutputStream os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeUTF(info+"-"+username+"-"+friendUsername);
        System.out.println("正在聊天中,退出输入exit");
        while (true){
            String msg = sc.nextLine();
            if("exit".equals(msg)) {
                System.out.println("退出成功");
                dos.close();
                socket.close();
                break;
            }
            dos.writeUTF(msg);
            dos.flush();
        }
    }

}

ClientReaderThread类

import java.io.DataInputStream;
import java.io.InputStream;
import java.net.Socket;

public class ClientReaderThread extends Thread{
    private Socket socket;
    public ClientReaderThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while (true) {
                try {
                    String msg = dis.readUTF();
                    System.out.println(msg);
                } catch (Exception e) {
                    System.out.println(socket.getRemoteSocketAddress()+"自己下线了");
                    dis.close();
                    socket.close();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 Friend类


public class Friend {
    private String account;
    private boolean state;

    public Friend(String account, boolean state) {
        this.account = account;
        this.state = state;
    }


    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public boolean getState() {
        return state;
    }

    public void setState(boolean state) {
        this.state = state;
    }

    @Override
    public String toString() {
        return "Friend{" +
                "account='" + account + '\'' +
                ",state='" + state + '\'' +
                '}';
    }
}

 MainThread类


import jdk.swing.interop.SwingInterOpUtils;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;

public class MainThread extends Thread{
    private static String username;
    @Override
    public void run() {
        star();
    }
    private static void star() {
        while (true) {
            Scanner sc = new Scanner(System.in);
            System.out.println("----------登录界面----------");
            System.out.println("1.登录");
            System.out.println("2.退出");
            String str  = sc.nextLine();
            switch (str){
                case "1":
                    login();
                    break;
                case "2":
                    return;
                default:
                    System.out.println("输入有误");

            }

        }

    }
    private static void login() {
        Scanner sc = new Scanner(System.in);
        String rightAccount;
        while(true) {
            System.out.println("请输入你的账号:");
            String accountNum = sc.next();
            rightAccount = comfirmAccount(accountNum);
            if(rightAccount.equals("-1")){
                System.out.println("账号不存在");
            }else{
                boolean info1 = false;
                for (user u2:Server.userList){
                    if(u2.getAccount().equals(rightAccount)){
                        try {
                            String[][] b1 = Server.Read(Server.file);
                            if(Boolean.parseBoolean(b1[Server.userList.indexOf(u2)][0])){
                                System.out.println("账号已被登录,请退出登陆后再重新登录");
                            }else{
                                username = accountNum;
                                info1 = true;
                                break;
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if(info1) break;

            }

        }
        while (true) {
            System.out.println("请输入你的密码:");
            String passwordNum = sc.next();
            boolean sec = false;
            for (user u2:Server.userList){
                if(u2.getAccount().equals(rightAccount) && u2.getPassword().equals(passwordNum)){
                    try {
                        int index1 = Server.userList.indexOf(u2);
                        String[][] b1 = Server.Read(Server.file);
                        for (int i = 0; i < b1.length; i++) {
                            Server.userList.get(i).setState(Boolean.parseBoolean(b1[i][0]));
                            if(i == index1) {
                                Server.userList.get(i).setState(true);
                            }
                        }
                        Server.Write(Server.file,Server.userList);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    sec = true;
                    break;
                }
            }
            if(sec == true){
                System.out.println("登录成功");
                operatorMenu();
                break;
            }else {
                System.out.println("密码有误");
            }
        }
    }


    private static void operatorMenu() {
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("----------操作界面----------");
            System.out.println("请输入操作数字(输入exit或者7退出)");
            System.out.println("1.添加好友");
            System.out.println("2.删除好友");
            System.out.println("3.显示好友及其状态");
            System.out.println("4.一对一聊天");
            System.out.println("5.群聊");
            System.out.println("6.建立群聊");
            System.out.println("7.退出");
            String str  = sc.nextLine();
            switch (str){
                case "1":
                    System.out.println("确定要添加好友操作吗?y/n");
                    String comfirmNum1 = sc.nextLine();
                    if(comfirmNum1.equals("Y") || comfirmNum1.equals("y")){
                        friendAdd();
                    }
                    break;
                case "2":
                    System.out.println("确定要删除好友操作吗?y/n");
                    String comfirmNum2 = sc.nextLine();
                    if(comfirmNum2.equals("Y") || comfirmNum2.equals("y")){
                        friendRemove();
                    }
                    break;
                case "3":
                    friendStateShow();
                    break;
                case "4":
                    System.out.println("确定要进行一对一聊天吗?y/n");
                    String comfirmNum3 = sc.nextLine();
                    if(comfirmNum3.equals("Y") || comfirmNum3.equals("y")){
                        OneChat();
                    }
                    break;
                case "5":
                    System.out.println("确定要进行群聊天吗?y/n");
                    String comfirmNum4 = sc.nextLine();
                    if(comfirmNum4.equals("Y") || comfirmNum4.equals("y")){
                        lotChat();
                    }
                    break;
                case "6":
                    System.out.println("确定要建立群聊吗?y/n");
                    String comfirmNum5 = sc.nextLine();
                    if(comfirmNum5.equals("Y") || comfirmNum5.equals("y")){
                        setGroup();
                    }
                    break;
                case "7":
                    exitExe();
                    System.out.println("退出成功");
                    return;
                case "exit":
                    exitExe();
                    System.out.println("退出成功-exit");
                    return;
                default:
                    System.out.println("输入有误,请重新输入!!!");
                    break;
            }

        }

    }

    private static void exitExe() {
        for (user user : Server.userList) {
            String[][] b1 = new String[6][10];
            try {
                b1 = Server.Read(Server.file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < b1.length; i++) {
                if(b1[i] == null) break;
                Server.userList.get(i).setState(Boolean.parseBoolean(b1[i][0]));
            }
            if(user.getAccount().equals(username)){
                user.setState(false);
                try {
                    Server.Write(Server.file,Server.userList);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    private static void OneChat() {
        Scanner sc = new Scanner(System.in);
        System.out.println("你的好友有:");
        friendStateShow();
        while (true) {
            System.out.println("请输入你想要聊天的对象");
            String friendUsername = sc.next();
            String[][] b1 = new String[6][10];
            try {
                b1 = Server.Read(Server.file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(comfirmAccount(friendUsername).equals("-1")){
                System.out.println("账号不存在");
            }else if(friendUsername.equals(username)){
                System.out.println("输入错误");
            }else {
                for (user u1:Server.userList){
                    if(u1.getAccount().equals(friendUsername)){
                        if(Boolean.parseBoolean(b1[Server.userList.indexOf(u1)][0])){
                            try {
                                Client.ClientMain(username,friendUsername,1);
                                break;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }else{
                            System.out.println("对面不在线");
                            break;
                        }
                    }
                }
            }
            break;
        }
    }

    private static void lotChat(){
        ArrayList<String> group = null;
        for (user u : Server.userList) {
            if(u.getAccount().equals(username)){
                group = u.getGroup();
                break;
            }
        }
        System.out.println("你的所有群聊如下");
        int i = 1;
        for (String s : group) {
            System.out.println(i + ": " +s);
            i++;
        }
        Scanner sc = new Scanner(System.in);
        int index;
        System.out.println("请输入群聊编号用于进入");
        index = sc.nextInt();
        while(index <= 0 || index > group.size()){
            System.out.println("输入错误,请重新输入");
            index = sc.nextInt();
        }
        String str = group.get(index-1);
        try {
            Client.ClientMain(username,str,2);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private static void setGroup() {
        Scanner sc = new Scanner(System.in);
        String[] b2 = new String[10];
        boolean myself = false;
        boolean tuichu = false;
        while(!tuichu){
            for (int i = 0; i < b2.length; i++) {
                b2[i] = null;
            }
            myself = false;
            System.out.println("请输入你要邀请进群的人,至少两个(中间用空格隔开)");
            String[] b3 = sc.nextLine().split(" ");
            if(b3.length < 2){
                tuichu = false;
                continue;
            }else{
                tuichu = true;
            }
            if(true){
                for (int i = 0; i < b3.length; i++) {
                    if(comfirmAccount(b3[i]).equals("-1")){
                        tuichu = false;
                        break;
                    }else{
                        tuichu = true;
                    }
                }
                if(tuichu == false){
                    continue;
                }
            }
            for (int i = 0; i < b3.length; i++) {
                if(b3[i].equals(username)) myself = true;
                b2[i] = b3[i];
            }
            tuichu = true;
        }
        String groupSyr = "";
        for (int i = 0; i < b2.length; i++) {
            if(b2[i] == null) break;
            groupSyr += (b2[i] + "-");
        }
        if(!myself){
            groupSyr += (username + "-");
        }
        for (int i = 0; i < b2.length; i++) {
            if(b2[i] == null) break;
            for (user user : Server.userList){
                if(b2[i].equals(user.getAccount())){
                    user.addGroup(groupSyr);
                    break;
                }
            }
        }
        if(!myself){
            for (user user : Server.userList) {
                if(user.getAccount().equals(username)){
                    user.addGroup(groupSyr);
                }
            }
        }
        System.out.println("创建成功");
        try {
            Server.Write(Server.file,Server.userList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void friendStateShow() {
        String[][] b1 = new String[6][10];
        try {
            b1 = Server.Read(Server.file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ArrayList<Friend> f1 = null;
        for (user u1:Server.userList){
            if(u1.getAccount().equals(username)){
                f1 = u1.getFriends();
            }
        }
        if(f1 == null){
            System.out.println("没有好友,快去添加吧");
            return;
        }
        for(Friend ff : f1){
            for (user u1:Server.userList){
                if(u1.getAccount().equals(ff.getAccount())){
                    System.out.println(ff.getAccount() + ":" + (Boolean.parseBoolean(b1[Server.userList.indexOf(u1)][0])?"在线":"不在线"));
                    break;
                }
            }
        }


    }

    private static void friendRemove() {
        Scanner sc = new Scanner(System.in);
        String[][] b1 = new String[6][10];
        try {
            b1 = Server.Read(Server.file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < b1.length; i++) {
            if(b1[i] == null) break;
            Server.userList.get(i).setState(Boolean.parseBoolean(b1[i][0]));
        }
        while (true) {
            System.out.println("请输入好友的账号,输入exit退出");
            String accountNum = sc.next();
            if(accountNum.contains("exit")) break;
            if(accountNum.equals(username)!=true){
                accountNum = comfirmAccount(accountNum);
                if(accountNum.equals("-1")){
                    System.out.println("账号不存在");
                }else{

                    for (user u1:Server.userList) {
                        if(u1.getAccount().equals(username)){
                            for(Friend ff : u1.getFriends()){
                                if(ff.getAccount().equals(accountNum)){
                                    u1.getFriends().remove(ff);
                                    break;
                                }
                            }

                        }
                    }
                    for (user u1:Server.userList) {
                        if(u1.getAccount().equals(accountNum)){
                            for(Friend ff : u1.getFriends()){
                                if(ff.getAccount().equals(username)){
                                    u1.getFriends().remove(ff);
                                    break;
                                }
                            }

                        }
                    }
                    try {
                        Server.Write(Server.file,Server.userList);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println("删除成功");
                    break;
                }
            }

        }
    }

    private static void friendAdd() {
        Scanner sc = new Scanner(System.in);
        String[][] b1 = new String[6][10];
        try {
            b1 = Server.Read(Server.file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < b1.length; i++) {
            if(b1[i] == null) break;
            Server.userList.get(i).setState(Boolean.parseBoolean(b1[i][0]));
        }

        while (true) {
            System.out.println("请输入好友的账号,输入exit退出");
            String accountNum = sc.next();
            if(accountNum.contains("exit")) break;
            accountNum = comfirmAccount(accountNum);
            if(accountNum.equals("-1")){
                System.out.println("账号不存在");
            }else{

                for (Friend u1:Server.firendList) {
                    if(u1.getAccount().equals(accountNum)){
                        for (user u2:Server.userList) {
                            if(u2.getAccount().equals(username)){
                                u2.addFriend(u1);
                                break;
                            }
                        }
                        for (user u2:Server.userList) {
                            if(u2.getAccount().equals(accountNum)){
                                for (Friend u3:Server.firendList) {
                                    if (u3.getAccount().equals(username)) {
                                        u2.addFriend(u3);
                                        System.out.println("添加成功");
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
                try {
                    Server.Write(Server.file,Server.userList);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }
    private static String comfirmAccount(String accountNum) {
        for(user uu : Server.userList){
            if(uu.getAccount().equals(accountNum)){
                return accountNum;
            }
        }
        return "-1";
    }
}

 server类


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Server {
    public static Map<Socket,String> onlines = new HashMap<>();
    public static ArrayList<user> userList = new ArrayList<>();
    public static ArrayList<Friend> firendList = new ArrayList<>();
    public static File file = new File("userData.txt");

    static {
        Friend friend1 = new Friend("111",false);
        Friend friend2 = new Friend("222",false);
        Friend friend3 = new Friend("333",false);
        Friend friend4 = new Friend("444",false);
        Friend friend5 = new Friend("555",false);
        Friend friend6 = new Friend("666",false);
        firendList.add(friend1);
        firendList.add(friend2);
        firendList.add(friend3);
        firendList.add(friend4);
        firendList.add(friend5);
        firendList.add(friend6);
        user user1 = new user("111", "111",false);
        user user2 = new user("222", "222",false);
        user user3 = new user("333", "333",false);
        user user4 = new user("444", "444",false);
        user user5 = new user("555", "555",false);
        user user6 = new user("666", "666",false);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        userList.add(user5);
        userList.add(user6);
    }








    public static void main(String[] args) throws Exception {

        if(!Server.file.exists()){
            file.createNewFile();
        }
        if (null == Server.file || 0 == Server.file.length() ) {
            //File file = new File("user.txt");
            System.out.println("文件为空!");
            //111的好友
            Server.userList.get(0).addFriend(firendList.get(1));
            Server.userList.get(0).addFriend(firendList.get(2));
            //222的好友
            Server.userList.get(1).addFriend(firendList.get(0));
            Server.userList.get(1).addFriend(firendList.get(2));
            Server.userList.get(1).addFriend(firendList.get(4));
            Server.userList.get(1).addFriend(firendList.get(3));
            //333的好友
            Server.userList.get(2).addFriend(firendList.get(0));
            Server.userList.get(2).addFriend(firendList.get(1));
            Server.userList.get(2).addFriend(firendList.get(4));
            //444的好友
            Server.userList.get(3).addFriend(firendList.get(1));
            Server.userList.get(3).addFriend(firendList.get(5));
            //555的好友
            Server.userList.get(4).addFriend(firendList.get(1));
            Server.userList.get(4).addFriend(firendList.get(2));
            //666的好友
            Server.userList.get(5).addFriend(firendList.get(3));

            //群聊加入:
            String group1 = "111-222-333-";
            String group2 = "111-222-444-";
            String group3 = "444-555-666-";
            Server.userList.get(0).addGroup(group1);
            Server.userList.get(0).addGroup(group2);
            Server.userList.get(1).addGroup(group1);
            Server.userList.get(1).addGroup(group2);
            Server.userList.get(2).addGroup(group1);
            Server.userList.get(3).addGroup(group2);
            Server.userList.get(3).addGroup(group3);
            Server.userList.get(4).addGroup(group3);
            Server.userList.get(5).addGroup(group3);
        }
        try {
            String[][] read = Read(file);
            for (int i = 0; i < read.length; i++) {
                if (read[i][1]!= null) {
                    String[] ReadStr = read[i][1].split("-");
                    for(int j = 0; j < ReadStr.length;j++){
                        if(ReadStr[j] == null){
                            break;
                        }else if(ReadStr[j].equals("111")){
                            Server.userList.get(i).addFriend(Server.firendList.get(0));
                        }else if(ReadStr[j].equals("222")){
                            Server.userList.get(i).addFriend(Server.firendList.get(1));
                        }else if(ReadStr[j].equals("333")){
                            Server.userList.get(i).addFriend(Server.firendList.get(2));
                        }else if(ReadStr[j].equals("444")){
                            Server.userList.get(i).addFriend(Server.firendList.get(3));
                        }else if(ReadStr[j].equals("555")){
                            Server.userList.get(i).addFriend(Server.firendList.get(4));
                        }else if(ReadStr[j].equals("666")){
                            Server.userList.get(i).addFriend(Server.firendList.get(5));
                        }
                    }
                }
                if(read[i][2] != null){
                    String[] ReadStr = read[i][2].split("#");
                    for(int j = 0; j < ReadStr.length;j++){
                        if(ReadStr[j] == null){
                            break;
                        }else {
                            Server.userList.get(i).addGroup(ReadStr[j]);
                        }
                    }
                }
            }
            Write(file, Server.userList);
        } catch (IOException e) {
            e.printStackTrace();
        }


        System.out.println("服务端启动");
        ServerSocket serverSocket = new ServerSocket(8888);
        while (true) {
            Socket socket = serverSocket.accept();
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            String str = dis.readUTF();
            String[] str1 = str.split("-");
            if(str1[0].equals("1")){
                String username = str1[1];
                String friendUsername = str1[2];
                Server.onlines.put(socket, username);
                System.out.println(Server.onlines);
                System.out.println(username + "上线了");
                new ServerReaderThread(socket, username, friendUsername, 1).start();
            }else if(str1[0].equals("2")){
                String username = str1[1];
                String friendUsername = str1[2];
                Server.onlines.put(socket, username);
                System.out.println(Server.onlines);
                System.out.println(username + "上线了");
                new ServerReaderThread(socket, username, friendUsername, 2).start();
            }

        }
    }
    public static void Write(File file, ArrayList<user> userList) throws IOException {
        FileWriter fw = new FileWriter(file,false);
        BufferedWriter bw = new BufferedWriter(fw);
        for (user a:userList){
            bw.write(String.valueOf(a.getState())+",");
            if(a.getFriends() != null){
                for(Friend f : a.getFriends()){
                    bw.write(f.getAccount()+"-");
                }
                bw.write(",");
            }
            if(a.getGroup() != null){
                for (String ss : a.getGroup()) {
                    bw.write(ss+"#");
                }
                bw.write(",");
            }
            bw.newLine();
        }
        bw.close();
        fw.close();
    }

    public static String[][] Read(File file) throws IOException {
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String s;
        int j = 0;
        String[][] b1 = new String[6][10];
        while ((s = br.readLine()) != null)
        {
            String[] str = s.split(",");
            for (int i = 0; i < str.length; i++) {
                    b1[j][i] = str[i];
            }
            j++;
        }
        br.close();
        fr.close();
        return b1;
    }

}

 ServerReaderThread类


import java.io.*;
import java.net.Socket;

public class ServerReaderThread extends Thread{
    private Socket socket;
    private String username;
    private String friendUsername;
    private int info;

    public ServerReaderThread(Socket socket,String username,String friendUsername,int info){
        this.socket = socket;
        this.username = username;
        this.friendUsername = friendUsername;
        this.info = info;
    }
    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            while (true) {
                if(info == 1){
                    try {
                        String msg = dis.readUTF();
                        sendOneChat(msg,friendUsername,username);
                    } catch (Exception e) {
                        System.out.println(username + ":" + socket.getRemoteSocketAddress()+"下线了");
                        Server.onlines.remove(socket);
                        dis.close();
                        socket.close();
                        break;
                    }
                }else if(info == 2){
                    try {
                        String msg = dis.readUTF();
                    System.out.println(msg);
                        sendgropChat(msg,friendUsername,username);
                    } catch (Exception e) {
                        System.out.println(username + ":" + socket.getRemoteSocketAddress()+"下线了");
                        Server.onlines.remove(socket);
                        dis.close();
                        socket.close();
                        break;
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void sendgropChat(String msg,String friendUsername,String username) throws IOException {
        String[] gropPersons = friendUsername.split(",");
        for (int i = 0; i < gropPersons.length; i++) {
            for (Socket onlineSocket: Server.onlines.keySet()) {
                if(Server.onlines.get(onlineSocket).equals(gropPersons[i]) && !Server.onlines.get(onlineSocket).equals(username)){
                    OutputStream os = onlineSocket.getOutputStream();
                    DataOutputStream dos = new DataOutputStream(os);
                    dos.writeUTF(username +" :  "+ msg);
                    dos.flush();
                }

            }
        }

    }

    private void sendOneChat(String msg,String friendUsername,String username) throws IOException {
        for (Socket onlineSocket: Server.onlines.keySet()) {
            if(Server.onlines.get(onlineSocket).equals(friendUsername)) {
                OutputStream os = onlineSocket.getOutputStream();
                DataOutputStream dos = new DataOutputStream(os);
                dos.writeUTF(username+" :  "+ msg);
                dos.flush();
                return;
            }

        }
    }



}

 ThreadStrat类

import java.io.IOException;

public class ThreadStart {
    public static void main(String[] args) {
        try {
            String[][] read = Server.Read(Server.file);
            for (int i = 0; i < read.length; i++) {
                if (read[i][1]!= null){
                    String[] ReadStr = read[i][1].split("-");
                    for(int j = 0; j < ReadStr.length;j++){
                        if(ReadStr[j] == null){
                            break;
                        }else if(ReadStr[j].equals("111")){
                            Server.userList.get(i).addFriend(Server.firendList.get(0));
                        }else if(ReadStr[j].equals("222")){
                            Server.userList.get(i).addFriend(Server.firendList.get(1));
                        }else if(ReadStr[j].equals("333")){
                            Server.userList.get(i).addFriend(Server.firendList.get(2));
                        }else if(ReadStr[j].equals("444")){
                            Server.userList.get(i).addFriend(Server.firendList.get(3));
                        }else if(ReadStr[j].equals("555")){
                            Server.userList.get(i).addFriend(Server.firendList.get(4));
                        }else if(ReadStr[j].equals("666")){
                            Server.userList.get(i).addFriend(Server.firendList.get(5));
                        }

                    }
                }
                if(read[i][2] != null){
                    String[] ReadStr = read[i][2].split("#");
                    for(int j = 0; j < ReadStr.length;j++){
                        if(ReadStr[j] == null){
                            break;
                        }else {
                            Server.userList.get(i).addGroup(ReadStr[j]);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        new MainThread().start();
    }
}

 user类


import java.util.ArrayList;

public class user {
    private String account;
    private String password;
    private ArrayList<Friend> friends;
    private ArrayList<String> group;
    private boolean state;

    public user() {
    }

    public user(String account, String password, boolean state) {
        this.account = account;
        this.password = password;
        this.friends = new ArrayList<>();
        this.state = state;
        this.group = new ArrayList<>();
    }
    public void addFriend(Friend friend){
        friends.add(friend);
    }
    public void addGroup(String persons){
        group.add(persons);
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public ArrayList<Friend> getFriends() {
        return friends;
    }

    public void setFriends(ArrayList<Friend> friends) {
        this.friends = friends;
    }

    public boolean getState() {
        return state;
    }

    public void setState(boolean state) {
        this.state = state;
    }

    public ArrayList<String> getGroup() {
        return group;
    }

    public void setGroup(ArrayList<String> group) {
        this.group = group;
    }


    @Override
    public String toString() {
        return "user{" +
                "account='" + account + '\'' +
                ", password='" + password + '\'' +
                ", friends=" + friends +
                ", group=" + group.toString() +
                ", state=" + state +
                '}';
    }
}

  • 25
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值