ServerSocket實現簡單的廣播系統

爪 哇發表於2020-09-26
/**
 * 服務端
 */
public class Server {
    // 儲存客戶端所有連線
    private static final List<Socket> socketList = Collections.synchronizedList(new ArrayList<>());
    // 監聽某個客戶端的輸入,然後進行廣播
    private static class Task implements Runnable {
        private final Socket socket;
        private final BufferedReader reader;
        public Task(Socket socket) throws IOException {
            this.socket = socket;
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
        @Override
        public void run() {
            try {
                String msg;
                while ((msg = reader.readLine()) != null) {
                    for (Socket skt : socketList) {
                        if (socket == skt) { continue; }
                        try {
                            PrintStream ps = new PrintStream(skt.getOutputStream());
                            ps.println(msg); // 注意這裡的換行
                        } catch (IOException e) {
                            socketList.remove(skt);
                        }
                    }
                }
            } catch (IOException e) {
                socketList.remove(socket);
            }
        }
    }
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        while (true) {
            Socket socket = serverSocket.accept(); // 阻塞
            System.out.println("socket => " + socket);
            socketList.add(socket);
            new Thread(new Task(socket)).start();
        }
    }
}
/**
 * 客戶端
 */
public class Client {
    // 讀取服務端的資料,並輸出到控制檯
    private static class Task implements Runnable {
        private final BufferedReader reader;
        public Task(Socket socket) throws IOException {
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
        @Override
        public void run() {
            try {
                String msg;
                while ((msg = reader.readLine()) != null) {
                    System.out.println(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket socket = new Socket("127.0.0.1", 8080);
        new Thread(new Task(socket)).start();
        PrintStream ps = new PrintStream(socket.getOutputStream());
        String msg;
        // 讀取控制檯輸入
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while ((msg = reader.readLine()) != null) {
            ps.println(msg);
        }
    }
}

 

相關文章