JAVA:Hashmap在通过套接字写两次后没有更改值

时间:2018-01-31 13:41:47

标签: java sockets hashmap

此应用程序应该发送和接收实现接口ContextObject

的自定义类型对象

此对象包含hashmap changes(问题),每当我在第一个.write 之后更改它时,它根本不会发生变化。

服务器

      TestingSession(Socket socket) throws Exception {

            try {
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

                this.socket = socket;

                while (!socket.isClosed()) {
                    // reads an object of Type contextObject 
                    ContextObject receivedCO =(ContextObject)  objectInputStream.readObject(); 



                     // if its of type UpdateContextObject , then it contains a "changes" hashmap, print it. 
                    if(receivedCO instanceof  UpdateContextObject) {
                        UpdateContextObject ob= (UpdateContextObject) receivedCO;
                        Map<String, String> map = ob.getChanges();
                        for (Map.Entry entry : map.entrySet())
                            logger.trace(entry.getKey() + "  " + entry.getValue());
                    }



                        // send back the results, (not important in this question.)   
                    List queryResult = Query.processQuery(receivedCO);
                    objectOutputStream.writeObject(queryResult);

                }

客户:

            Socket socket;
            socket = new Socket("127.0.0.1", 5050);

            ObjectInputStream objectInputStream = new 
            ObjectInputStream(socket.getInputStream());
            ObjectOutputStream objectOutputStream = new 
            ObjectOutputStream(socket.getOutputStream());


            UpdateContextObject updateCO = new UpdateContextObject();


            // not important, for later processing.
            updateCO.setTable("users");
            updateCO.setAttributes(new HashMap<>());


             // This map that doesnt get changed.
            Map<String,String> changes = new HashMap<>();
            changes.put("Id","1");
            updateCO.setChanges(changes);


            int i=0;
            while(true){
                i++;

                changes.put("Id",""+i);


                objectOutputStream.writeObject(updateCO);
                objectInputStream.readObject();

                changes.put("username","3");
                System.out.println(changes.get("Id"));
                if(i>50) break;
            }

服务器输出:

  

将Id设置为1

     

将Id设置为1

     

将Id设置为1

     

将Id设置为1

     

将Id设置为1

客户端输出:

  

1   2   3   4   五    ..

0 个答案:

没有答案