Java 服务器/客户端问题

标签 java arraylist

所以这是我们提出的问题:

You are given the following application-layer networking protocol for a simple client/server application.

A client can send tokens (words) to the server which adds them to a global tokens list in memory. The tokens list has a capacity of 10 different tokens. The tokens should be stored in the tokens list in descending (reverse) lexicographical order. There are three types of requests: SUBMIT, REMOVE and QUIT.

The protocol in detail:

  • Client request (a message send from client to server): SUBMIT token Server: If the tokens list is not yet full, add the token to the global list of tokens (if the list doesn’t contain that token yet) or ignore it (if the respective token was already in the list). In both cases, respond by sending message OK to the client. If the list is already full (contains 10 tokens), respond to the client with message ERROR. token stands for a string which doesn’t contain whitespace, see class Scanner (Java API). The tokens list should be sorted in descending lexicographical order at any time. Choose an appropriate data structure for representing the tokens list.
  • Client request: REMOVE token Server: If the tokens list contains token, remove it from the tokens list and reply to the client with message OK. Otherwise, reply with ERROR.
  • Client request: QUIT Server: Ends the connection to that client. No response.

Q1. Create a (non-enterprise-, non-servlet-) Java class for a server which can interact with clients via the Internet in compliance with the given protocol. Do not support concurrent handling of clients here, just the sequential dealing with clients (that is, only after the connection to a client has ended, a new client can connect to the server, and so on). The server should maintain only a single, global tokens list which is never emptied by the server unless by means of REMOVE requests (i.e., not a new empty tokens list for each connecting client).

这是我迄今为止的尝试:

公共(public)类服务器{

private Socket s;
private Scanner in;
private PrintWriter out;

public static void main(String[] args) throws IOException {
    ServerSocket server = new ServerSocket(6789);
    Server serverInstance = new Server();
    System.out.println("Server running. Waiting for a client to connect...");
    while(true) {
        serverInstance.s = server.accept();
        System.out.println("Client connected");
        serverInstance.run();
        System.out.println("Client disconnected. Waiting for a new client to connect...");
    }
}

public void run() {
    try {
        try {
            in = new Scanner(s.getInputStream());
            out = new PrintWriter(s.getOutputStream());
            doService(); // the actual service
        } finally {
            s.close();
        }
    } catch (IOException e) {
        System.err.println(e);
    }
}
public void doService() throws IOException {
    while(true) {
        if(!in.hasNext())
            return;
        String request = in.next();
        System.out.println("Request received: " + request);
        // (...) test for type of request here (not implemented)
        Request(request);
    }
}
public void Request(String request) {
    ArrayList<String> tokens = new ArrayList<String>(10);
    String amountStr = in.next();
    if(request.startsWith("SUBMIT")) {
        if(tokens.size() <= 10){
            out.println(tokens.add(amountStr)); //server response
            System.out.println( amountStr + " added to list");
        }
        else{System.out.println("Error");
        } 
    }
    else if(request.startsWith("REMOVE")) {
    out.println(tokens.remove(amountStr)); //server response
    System.out.println(amountStr + " removed from list");
    } 
    else if(request.equals("QUIT")){
    System.err.println("Program ended");
    }

    System.out.println(tokens);
    out.flush();
    }
}

公共(public)类客户端{

public static void main(String[] args) throws IOException {
     Socket s = new Socket("localhost", 6789);
     InputStream instream = s.getInputStream();
     OutputStream outstream = s.getOutputStream();
     Scanner in = new Scanner(instream);
     PrintWriter out = new PrintWriter(outstream);
     String request = "SUBMIT hello \n";
     out.print(request);
     out.flush();
     String response = in.nextLine();
     System.out.println("Token: " + response);
     s.close();
    }

}

Output:

Server running. Waiting for a client to connect...

Client connected

Request received: SUBMIT

hello added to list

[hello]

Client disconnected. Waiting for a new client to connect...

Client connected

Request received: SUBMIT

hi added to list

[hi]

Client disconnected. Waiting for a new client to connect...

所以我已经让服务器正常工作,客户端可以连接到它并向数组列表提交一个 token ,但是每次新客户端向列表添加 token 时,它只是替换旧的 token ,而不是添加到数组中。 [hi] 取代了 [hello],而不是成为 [hello, hi]。

对于 REMOVE 和 QUIT 请求,我真的不知道如何让它们正常工作。

任何帮助将不胜感激。

最佳答案

在我看来,这是因为每次客户端请求服务时您都会声明一个新的ArrayList。你调用run,它调用Request,它每次都声明一个新的ArrayList

PS:更改Request方法的名称,应以小写开头:request()

关于Java 服务器/客户端问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29238109/

相关文章:

java - 将具体对象列表转换为抽象类型

java - onNotificationPosted 一段时间后没有被调用

java : remove words from ArrayList<String>

java - 使用数组列表洗牌的输出不显示

java - 在Java中将集合的集合转换为列表的列表

java - 不使用 CSS 更改小部件外观

JavaFX DatePicker - 删除文本框

java - 如何加快自定义对象比较器的速度

java - fragment 中传递的 Arraylist 为空

java - 按每个子列表中的第一个数字排序 List<List<Integer>>