Java聊天室(持续更新)

为了加深Java网络编程TCP编程的印象,开始练习一个小项目
项目初步实现了聊天室(先占个坑)
server.java

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class Server {
    private int port;
    private List<Socket> list;
    private ServerSocket serverSocket;
    public Server(int port){
        list = new ArrayList<>();
        this.port = port;
        try{
            serverSocket = createServer(port);
        }catch (IOException ie){
            System.out.println("the port is wrong");
            throw new RuntimeException(ie);
        }
    }
    private static ServerSocket createServer(int port) throws IOException {
        return new ServerSocket(port);
    }
    public void run(){
        Executor e = Executors.newFixedThreadPool(5);
        try{
            while (true) {
                Socket socket = serverSocket.accept();//阻塞,等待用户连接
                list.add(socket);
                e.execute(new Worker(socket));
            }
        }catch (IOException ie){
            ie.printStackTrace();
        }
    }
    public void printAllClints(String string) throws IOException{
        for(Socket w:list){
            if(!w.isClosed()) {
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(w.getOutputStream()));
                bw.write(string);
                bw.flush();
            }else{
                //迭代器里面不可以修改:list.remove(w);
            }
        }
    }
    private class Worker implements Runnable{
        BufferedWriter w;
        BufferedReader i;
        Socket socket;
        Worker(Socket s){
            socket = s;
        }
        @Override
        public void run() {
            try{
                System.out.println("用户连接成功");
                i = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                w = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                w.write("hello clint.欢迎使用本聊天室"+"\n");
                w.flush();
                while(true){
                    String str = i.readLine();//阻塞,等待socket中的数据被用户写入
                    if(str.equalsIgnoreCase("quit")){
                            w.close();
                            i.close();
                            socket.close();
                            break;
                    }else{
                        //....
                        System.out.println(str);
                        for(int i = 0;i<list.size();i++){
                            if(list.get(i).isClosed())
                                list.remove(i);
                        }
                        printAllClints(str + System.getProperty("line.separator"));
                        System.out.println("----------");
                    }
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

ClinkSocket.java

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

public class ClintSocket {
    Date d = new Date();
    private Clint clint;
    private Socket socket;
    private BufferedWriter bw;
    private BufferedReader br;
    ClintSocket(Clint clint,Socket socket){
        this.clint = clint;
        this.socket = socket;
        try {
            bw = new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream()));
            br = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
        } catch (IOException ie){
            ie.printStackTrace();
        }
    }
    public void run() {
        String tp;
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        try{
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        //打断线程
                        if(Thread.currentThread().isInterrupted()){
                            return;
                        }
                        System.out.println(read());//从socket读出数据
                    }
                }
            });
            t.start();
            write(clint.getName()+"进入了聊天室"+"["+d+"]");
            while (true) {
                String sa = r.readLine();//从键盘读入
                if (sa.equalsIgnoreCase("quit")) {
                    write(clint.getName() + "退出了聊天室"+"["+d+"]");
                    write("quit");
                    break;
                } else {
                    write(clint.getName()+":"+sa+"["+d+"]" );//将信息送入socket,line.separator输出换行
                }
            }
            t.interrupt();//改变中断状态
            close();

        }catch (IOException ie){
            ie.printStackTrace();
        }
    }
    private void write(String s) {
        try {
            bw.write(s + System.getProperty("line.separator"));
            bw.flush();
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }
    private String read(){
        try {
            return br.readLine();
        } catch (IOException ie) {
            ie.printStackTrace();
            System.out.println("服务器异常关闭");
            Thread.currentThread().interrupt();
        }
        return null;
    }
    private void close(){
        try{
            br.close();
            bw.close();
            socket.close();
        }catch(IOException ie){
            ie.printStackTrace();
        }

    }
}

Clint.java

public class Clint {
    private String name;
    private String id;
    private String password;
    public Clint(String name,String id,String password){
        this.id = id;
        this.name = name;
        this.password = password;
    }
    public String getName() {
        return name;
    }
    public void Login(String id,String password){

    }
}

Main.java
打开服务端

public class Main {
    public static void main(String[] args) throws Exception {
        Server server = new Server(4242);
        server.run();
    }
}

创建3个客户端

import java.net.InetAddress;
import java.net.Socket;

public class Test1 {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket(InetAddress.getByName("127.0.0.1"), 4242);
        ClintSocket clintSocket =
                new ClintSocket(new Clint("小明", "11220", "5455"), s);
        clintSocket.run();
    }
}
import java.net.InetAddress;
import java.net.Socket;

public class Test2 {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket(InetAddress.getByName("127.0.0.1"), 4242);
        ClintSocket clintSocket =
                new ClintSocket(new Clint("小王", "11220", "5455"), s);
        clintSocket.run();
    }
}
import java.net.InetAddress;
import java.net.Socket;

public class Test3 {
    public static void main(String[] args) throws Exception {
        Socket s = new Socket(InetAddress.getByName("127.0.0.1"), 4242);
        ClintSocket clintSocket =
                new ClintSocket(new Clint("小李", "11220", "5455"), s);
        clintSocket.run();
    }
}

hello clint.欢迎使用本聊天室
小明进入了聊天室[Sat Oct 05 14:31:38 CST 2019]
小王进入了聊天室[Sat Oct 05 14:31:44 CST 2019]
小李进入了聊天室[Sat Oct 05 14:31:48 CST 2019]
小明:你好[Sat Oct 05 14:31:38 CST 2019]
小王:你好[Sat Oct 05 14:31:44 CST 2019]
你好
小李:你好[Sat Oct 05 14:31:48 CST 2019]

(未完待续)

发布了23 篇原创文章 · 获赞 4 · 访问量 843

猜你喜欢

转载自blog.csdn.net/qq_43656529/article/details/101726796
今日推荐