Java学习-包含私聊的多人聊天室

来源:互联网 发布:淘宝卖家怎么处理退货 编辑:程序博客网 时间:2024/05/16 11:25

Server.java

package com.anqi.tcp4;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;import java.util.ArrayList;import java.util.List;public class Server {    private List<MyChannel>all = new ArrayList<>();    public static void main(String[] args) throws IOException {        new Server().start();    }    public void start() throws IOException{        ServerSocket server = new ServerSocket(9998);        while(true){                Socket client = server.accept();                MyChannel channel = new MyChannel(client);                all.add(channel);//统一管理                new Thread(channel).start();//一条道路            }    }    /**     * 一个客户端一条道路     *  输入流     *  输入流     *  接收数据     *  发送数据     * @author Angel     *     */    private class MyChannel implements Runnable{        DataInputStream dis;        DataOutputStream dos;        private boolean isRunning = true;        private String name;        public MyChannel(Socket client){            try {                dis = new DataInputStream(client.getInputStream());                dos = new DataOutputStream(client.getOutputStream());                this.name = dis.readUTF();                System.out.println(this.name);                this.send("欢迎进入聊天室");                sendOthers(this.name+"进入了聊天室",true);            } catch (IOException e) {                isRunning = false;                CloseUtil.closeAll(dis,dos);            }        }        /**         * 读取数据         * @return         */        private String receive(){            String msg = null;            try {                msg = dis.readUTF();            } catch (IOException e) {                isRunning = false;                CloseUtil.closeAll(dis);                all.remove(this);//移除自身            }            return msg;        }        /**         * 发送数据         */        private void send(String msg){            if(msg == null  || msg.equals(""))                return;            try {                dos.writeUTF(msg);                dos.flush();            } catch (IOException e) {                isRunning = false;                CloseUtil.closeAll(dos);                all.remove(this);//移除自身            }        }        /**         * 发送给其他客户端         */        private void sendOthers(String msg,boolean sys){            //是否为私聊            if(msg.startsWith("@") && msg.indexOf(":")>-1){//私聊                //获取name                String name = msg.substring(1, msg.indexOf(":"));                String content = msg.substring(msg.indexOf(":")+1);                for (MyChannel others : all) {                    if(others.name.equals(name)){                        others.send(this.name+"对您悄悄地说:"+content);                    }                }            }else{                //遍历容器            for (MyChannel others : all) {                if(others == this)                    continue;                if(sys)//系统信息                    others.send("系统提示:"+msg);                else                    //发送给其他客户端                    others.send(this.name+"对所有人说"+msg);                }            }        }        public void run() {            while(isRunning){                sendOthers( receive(),false);            }        }    }}

Client.java

package com.anqi.tcp4;import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.net.Socket;public class Client {    public static void main(String[] args) throws IOException, IOException {        System.out.println("请输入名称:");        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));        String name = br.readLine();        if(name.equals("")){            return;        }        Socket client = new Socket("localhost",9998);        //控制台输入流        new Thread(new Send(client,name)).start();//一条路径        new Thread(new Receive(client)).start();//一条路径    }}

Send.java

package com.anqi.tcp4;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.net.Socket;/** * 发送数据 * @author Angel * */public class Send implements Runnable{    //控制台输入流    private BufferedReader console;    //管道输出流    private DataOutputStream dos;    //控制线程    private String name;    private boolean isRunning = true;    public Send(){        console = new BufferedReader(                new InputStreamReader(System.in));    }    public Send(Socket client,String name){        this();        try         {            dos = new DataOutputStream(client.getOutputStream());            this.name = name;            send(this.name);            System.out.println(this.name);        } catch (IOException e) {            isRunning = false;            CloseUtil.closeAll(dos,console);        }    }    /**     * 从控制台接收数据     * @return     */    private String getMsgFromConsole(){        try {            return console.readLine();        } catch (IOException e) {        }        return "";    }    /**     * 1.从控制台接收数据     * 2.发送数据     */    public void send(String msg){        if(msg != null && !msg.equals("")){            try {                dos.writeUTF(msg);                dos.flush();            } catch (IOException e) {                isRunning = false;                CloseUtil.closeAll(dos,console);            }        }    }    public void run() {            //线程体            while(isRunning){                send( getMsgFromConsole()) ;            }        }}

Receive.java

package com.anqi.tcp4;import java.io.DataInputStream;import java.io.IOException;import java.net.Socket;/** * 接收数据 * @author Angel * */public class Receive implements Runnable{    //输入流    private DataInputStream dis;    //线程控制    private boolean isRunning = true;    Receive(){    }    Receive(Socket client){        try {            dis = new DataInputStream(client.getInputStream());        } catch (IOException e) {            isRunning = false;            CloseUtil.closeAll(dis);        }    }    /**     * 接收数据     * @return     */    public String receive(){        String msg = "";        try {            msg = dis.readUTF();        } catch (IOException e) {            isRunning = false;            CloseUtil.closeAll(dis);        }        return msg;    }    public void run() {        //线程体        while(isRunning){            System.out.println(receive());        }    }}

CloseUtil.java

package com.anqi.tcp4;import java.io.Closeable;import java.io.IOException;/** * 关闭流的方法 * @author Angel * */public class CloseUtil {    public static void closeAll(Closeable ... io){        for (Closeable closeable : io) {            if (closeable != null)                try                {                    closeable.close();                } catch (IOException e) {}        }    }}
原创粉丝点击