ServerSocket实现简单的广播系统

/**
 * 服务端
 */
public class Server {
    // 保存客户端所有连接
    private static final ListSocket 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);
        }
    }
}

 

最新回复(0)
    /jishuoGLlOXuAlI1RrK_2BHPYylrdVuZXN75_2BiSkAiX9a4x3jE_3D
    8