为什么不会从多个客户端请求中获得arraylist商店值?

时间:2014-03-20 15:42:16

标签: java arraylist

我正在从客户端向服务器发送字符串。服务器正在接收此字符串。我将它转换为整数并将其添加到arraylist。我希望在会话期间添加的所有整数都添加到arraylist中,并将arraylist的所有值的总和返回给客户端。然而,arrayList只包含最新的值而且不会增长。它不存储前一个值(即,arraylist总是大小为1,sum总是0 +最近的整数,而不是所有整数的总和)。关于我做错的任何建议都会很棒。感谢

//Client Side
public class ConversionClient {

public static void main(String[] args) throws IOException {
    Socket s = new Socket("localhost", 8888);
    InputStream instream = s.getInputStream();
    OutputStream outstream = s.getOutputStream();
    Scanner in = new Scanner(instream);
    PrintWriter out = new PrintWriter(outstream);

    String request = "CONVERT_TO_POUNDS 10\n";
    out.print(request);
    out.flush();
    String response = in.nextLine();
    System.out.println("Receiving: " + response);   

    request = "CONVERT_TO_POUNDS 50\n";
    out.print(request);
    out.flush();
    response = in.nextLine();
    System.out.println("Receiving: " + response);

    s.close();
}

} 


//Server Side
 public void handleConversionRequest(String request) {
    String amountStr = in.next();
    int amount = Integer.valueOf(amountStr);
    ArrayList<Integer> numList = new ArrayList<Integer>();
    numList.add(amount);
    //System.out.println("Size:" +numList.size());
    System.out.println("Received from client: " + amount);

    if(request.equals("CONVERT_TO_POUNDS")) {
        int sum=0;
        for (int i=0; i<numList.size(); i++){
            sum+=numList.get(i);
        }

        out.println(sum); //server response
        System.out.println("Sending conversion result to client:"+sum);
    }  

    else
        System.err.println("Unknown request!");
    out.flush();
}

 }

1 个答案:

答案 0 :(得分:2)

  

它不存储先前的值(即arraylist总是大小为1)

这是正常的,因为您的handleConversionRequest()方法每次调用时都会创建一个新列表:

public void handleConversionRequest(String request) {
    String amountStr = in.next();
    int amount = Integer.valueOf(amountStr);
    ArrayList<Integer> numList = new ArrayList<Integer>(); // <-- HERE

使用此方法创建列表;更重要的是,ArrayList不是线程安全的,您可能想要使用CopyOnWriteArrayList