Javaネットワークプログラミングのチャットルームの構築

42332 ワード

コンソールベースのJavaチャットルーム
IDEAユーザーは私のgithubプロジェクトページに直接ダウンロードして使用することができます.https://github.com/yanghao1550/Chat-Room-Java
この小さなプロジェクトは主にSocketとマルチスレッドの入門知識を使用して完成します.Chat.javaはサーバ側Client.javaはクライアントである
使用する場合は、サーバ側を開いてから、複数のクライアントを開いてサーバ側に接続してコミュニケーションする必要があります.
主な機能は次のとおりです.
1、新しいユーザーを歓迎し、新しいユーザーがオンラインになったことを放送する
2、グループチャットおよびチャット機能(デフォルトはグループチャット、チャット方式は「@ユーザー名:message」と入力)
3、ユーザー退出注意
クライアントはnew Socket()のサーバー側IPアドレスの正確性を保証する必要があり、サーバー側が本機であれば"localhost"を入力すればよい
コード#コード#
Chat.java
/**
 *      :    
 *
 * @Author Nino 2019/10/23
 */
public class Chat {
    private static CopyOnWriteArrayList<Channel> all = new CopyOnWriteArrayList<>();

    public static void main(String[] args) throws IOException{
        System.out.println("----Server----");
        ServerSocket server = new ServerSocket(8888);
        while (true) {
            Socket client = server.accept();
            System.out.println("       ");
            Channel c = new Channel(client);
            //        
            all.add(c);
            new Thread(c).start();
        }
    }

    static class Channel implements Runnable{
        private Socket client;
        private DataInputStream dis;
        private DataOutputStream dos;
        private boolean isRunning;
        private String name;

        public Channel(Socket client) {
            this.client = client;
            try {
                dis = new DataInputStream(client.getInputStream());
                dos = new DataOutputStream(client.getOutputStream());
                isRunning = true;
                name = receive();
                this.send("  ");
                this.sendOthers(name + "      ",true);
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }
        }

        //     
        public String receive() {
            String msg = "";
            try {
                msg = dis.readUTF();
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }
            return msg;
        }

        //     
        public void send(String msg) {
            try {
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }
        }

        /**
         *         
         *    @xxx:
         * @param msg
         */
        public void sendOthers(String msg,boolean isSys) {
            boolean isPrivate = msg.startsWith("@");
            if (isPrivate) {
                int index = -1;
                if ((index = msg.indexOf(":")) == -1) {
                    index = msg.indexOf(":");
                }
                String targetName = msg.substring(1, index);
                msg = msg.substring(index + 1);
                for (Channel other : all) {
                    if (other.name.equals(targetName)) {
                        other.send(name + "      :" + msg);
                    }
                }
            } else {
                for (Channel other : all) {
                    if (other == this) {
                        continue;
                    } else if (!isSys) { //     
                        other.send(name + ": " + msg);
                    } else { //     
                        other.send(msg);
                    }
                }
            }

        }

        //     
        public void release() {
            isRunning = false;
            Utils.close(dos, dis, client);
            all.remove(this);
            sendOthers(name + "   ", true);
        }

        @Override
        public void run() {
            while (isRunning) {
                //     
                String msg = receive();
                if (!msg.equals("")) {
                    //     
                    sendOthers(msg,false);
                }
            }
        }

        public String getName() {
            return name;
        }
    }
}

Client.java
/**
 *      :   
 *
 * @Author Nino 2019/10/23
 */
public class Client {
    public static void main(String[] args) throws IOException {
        System.out.println("----Client----");

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("      :");
        String name = br.readLine();

        Socket client = new Socket("localhost", 8888);

        new Thread(new Send(client,name)).start();
        new Thread(new Receive(client)).start();

    }

    private static class Utils {
        public static void close(Closeable... targets) {
            for (Closeable target : targets) {
                try {
                    if (null != target) {
                        target.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class Receive implements Runnable {
        private DataInputStream dis;
        private Socket client;
        private boolean isRunning;

        public Receive(Socket client) {
            isRunning = true;
            this.client = client;
            try {
                dis = new DataInputStream(client.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }
        }

        private void receive() {
            try {
                String msg = dis.readUTF();
                System.out.println(msg);
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }
        }

        private void release() {
            isRunning = false;
            Utils.close(dis, client);
        }


        @Override
        public void run() {
            while (isRunning) {
                receive();
            }
        }
    }

    private static class Send implements Runnable {
        private BufferedReader console;
        private DataOutputStream dos;
        private Socket client;
        private boolean isRunning;
        private String name;

        public Send(Socket client, String name) {
            this.name = name;
            isRunning = true;
            this.client = client;
            console = new BufferedReader(new InputStreamReader(System.in));
            try {
                dos = new DataOutputStream(client.getOutputStream());
                //     
                send(name);
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }
        }

        private void release() {
            isRunning = false;
            Utils.close(dos, client);
        }

        private String read() {
            String msg = "";
            try {
                msg = console.readLine();
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }
            return msg;
        }

        private void send(String msg) {
            try {
                dos.writeUTF(msg);
                dos.flush();
            } catch (IOException e) {
                e.printStackTrace();
                release();
            }
        }

        @Override
        public void run() {
            while (isRunning) {
                String msg = read();
                if (!msg.equals("")) {
                    send(msg);
                }
            }
        }
    }
}