如何客户端类可以从服务器类得到一个对象列表,基于socket编程

vs91vp4v  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(190)

我试着写一个程序,它可以处理多个客户机连接,我想从服务器端得到一个完整的客户机列表,以便从客户机端管理它们。当我试图获取列表或者甚至试图创建singleton来获取那个对象时,我只得到一个空列表。我怎样才能得到那个名单?这是我的服务器类:

public class Server {

public final static int PORT = 1978;

public static List<ClientHandler> clients = new ArrayList<>();
private static ExecutorService executorService = Executors.newFixedThreadPool(4);

public static List<ClientHandler> getClients() {
    return clients;
}

public static void main(String[] args)  throws IOException {

    clients =  Collections.synchronizedList(clients);

    ServerSocket listener = new ServerSocket(PORT);

    while(true) {
        System.out.println("[SERVER] Waiting for client connection...");
        Socket client = listener.accept();
        System.out.println("[SERVER] Connected to client!");

        ClientHandler clientThread = new ClientHandler(client,clients);
        clients.add(clientThread);
        executorService.execute(clientThread);

    }
}}

这是我的客户端类:

public class Client {
private static final String SERVER_IP ="";
private static final int SERVER_PORT = 1978;

public static void main(String[] args) throws IOException {
    Socket socket = new Socket(SERVER_IP,SERVER_PORT);

    ServerConnection serverConn = new ServerConnection(socket);

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
    new Thread(serverConn).start();
    while(true) {

        String command = keyboard.readLine();

        if(command.equalsIgnoreCase("quit")) break;
        out.println(command);
    }
    socket.close();
    System.exit(0);

}

}下面是我的服务器连接类:

public class ServerConnection implements Runnable {

private Socket server;
private BufferedReader in;

public ServerConnection(Socket socket) throws IOException {
    this.server = socket;
    in = new BufferedReader(new InputStreamReader(server.getInputStream()));
}

@Override
public void run() {
        try {
            System.out.println("CONNECT");
            while(true) {
                String  serverResponse = in.readLine();
                if(serverResponse== null) break;
                System.out.println("Server says: " + serverResponse);
                System.out.println(Server.getClients());
           }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题