HashMap数据不会将新数据附加到ArrayList中

时间:2014-02-17 08:19:19

标签: java sockets serversocket

我使用以下代码从Applet客户端连接java socket。我将客户端的IP地址和一些随机数存储在以下代码中addNewClient()函数中发生的每个新连接中。我将此信息存储在HashMap中。我在此ArrayList的{​​{1}}中添加了更多客户信息。

如果HashMap中已有一些客户信息,我需要仔细阅读。我正在使用ArrayListSocketConnection课程中尝试这一点。

我看到的问题是,我在Iterator中添加了3个客户端信息。但是,当我使用ArrayList读取它时,它只能获得最后添加的客户端信息,而其他KEYS只是变空。但是,与此同时,它正确地将ArrayList大小赋予Iterator

有些专家可以参考我下面的完整代码,并告诉我那里可能出现什么问题?

3

更新:根据Amrish建议,更改了以下代码,它解决了问题。

public class DataSharingSocketListner {
            public static void main(String[] args) {

                System.out.println("client trying to connect before thread creation");

                Thread thr = new Thread(new SocketThread());
                thr.start();
            }
        }

        class SocketThread implements Runnable {

            HashMap<String, ClientInfo> clientInfo = new HashMap<String, ClientInfo>();

            ArrayList<HashMap<String, ClientInfo>> myList = new ArrayList<HashMap<String, ClientInfo>>();

            @Override
            public void run() {
                try {
                    System.out.println("client trying to connect after thread creation");

                    ServerSocket server = new ServerSocket(8080);
                    while (true) {

                        SocketConnection client = new SocketConnection(server.accept(), clientInfo, myList);
                        client.start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

        class SocketConnection extends Thread {
            InputStream input;
            PrintWriter output;
            Socket socket;
            ObjectOutputStream out = null;
            OutputStream clientOutput;
            Scanner scannerObj;
            HashMap<String, byte[]> hm;
            InetAddress addr;

            HashMap<String, ClientInfo> clientinfo;

            ArrayList<HashMap<String, ClientInfo>> clientList;

            public SocketConnection(Socket socket, HashMap<String, ClientInfo> clientInfo, ArrayList<HashMap<String, ClientInfo>> myList) {

                super("Thread 1");

                this.socket = socket;
                //this.hm = dataHashMap;
                this.clientinfo = clientInfo;
                this.clientList = myList;

                try {

    // IT IS PRINTING TOTAL SIZE 3 SUCCESSFULLY HERE
                    int totalClientList = clientList.size();
                    System.out.println("totalClientList: " + totalClientList);

                    if ( totalClientList>0 )
                    {
                        for (int i=0; i<totalClientList; i++)
                        {
                            System.out.println("client list reading " + i);

                            HashMap<String, ClientInfo> tmpData = (HashMap<String, ClientInfo>) clientList.get(i);

  // IT IS GETTING ONLY THE LAST KEY, OTHER KEYS ARE SHOWING EMPTY
                            Set<String> key = tmpData.keySet();
                            Iterator it = key.iterator();

                            while (it.hasNext()) {
                                System.out.println("hasNexthasNext");
                                String hmKey = (String)it.next();
                                ClientInfo hmData = (ClientInfo) tmpData.get(hmKey);

                                System.out.println("Key: "+hmKey +" & Data: "+hmData.getRandomNo());
                                it.remove(); // avoids a ConcurrentModificationException
                            }
                        }
                        // TO ADD NEW CLIENT EVERY TIME
                        addNewClient();
                    }
                    else {
                        System.out.println("Client List shows empty");

                        // TO ADD NEW CLIENT EVERY TIME
                        addNewClient();
                    }

                    // Not used yet, will be used
                    input = socket.getInputStream();
                    scannerObj = new Scanner(socket.getInputStream());
                    clientOutput = socket.getOutputStream();


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            public int genRandomNumber() {
                Random r = new Random( System.currentTimeMillis() );
                return 10000 + r.nextInt(20000);
            }
            String getLocalIP () {
                InetAddress inetAddress = null;
                String ipAddress = null;
                try {
                    inetAddress = InetAddress.getLocalHost();
                    ipAddress = inetAddress.getHostAddress();
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("ipAddress : " + ipAddress);

                return ipAddress;
            }
            void addNewClient () {

                String ipAddress = getLocalIP();

                if ( ipAddress!=null )
                {
                    ClientInfo clientobj = new ClientInfo();

                    clientobj.setIPAdd(ipAddress);
                    int randno =  genRandomNumber();
                    System.out.println("genRandomNumber() : " + randno);
                    clientobj.setRandomNo(randno);

                    String key = String.valueOf(randno);

                    clientinfo.put(key, clientobj);

                    clientList.add(clientinfo);
                }
            }

            @Override
            public void run() {

                System.out.println("Going to Read client data");

                //do something
                {
                    String hostIP = addr.getHostAddress() ;
                    System.out.println("hostIP: " + hostIP);

                    //do something
                }
            }



        }

        class ClientInfo {

            private String IPAddress;
            private long RandomNumber;
            private byte[] data;

            public static void main(String []args) {
                System.out.println("Client info Main");
            }

            //Setter
            void setIPAdd (String ip) {
                System.out.println("setIPAdd called");
                IPAddress = ip;
            }
            void setRandomNo (long randomno) {
                RandomNumber = randomno;
            }
            void setImageData (byte[] imgData) {
                data = imgData;
            }

            //Getter 
            String getIPAdd () {
                return IPAddress;
            }
            long getRandomNo () {
                return RandomNumber;
            }
            byte[] getImageData () {
                return data;
            }

        }

3 个答案:

答案 0 :(得分:1)

你的Arraylist有3个hashmap,但每个hashmap只有一个对象。因此,您将大小设置为3,但是当您遍历hashmap时,只返回一个对象。

答案 1 :(得分:0)

这里的问题是你在比较两件事:

int totalClientList = clientList.size();

这将为您提供列表中的客户数量:

 HashMap<String, ClientInfo> tmpData = (HashMap<String, ClientInfo>) clientList.get(i);
 Set<String> key = tmpData.keySet();

这将为您提供i'th client的密钥。这与total clients.

不同

您应该做的是drop List of hashmaps,只需使用single HashMap来跟踪所有客户。

希望这有帮助。

将您的SocketThread更改为删除列表

class SocketThread implements Runnable {

    HashMap<String, ClientInfo> clientInfo = new HashMap<String, ClientInfo>();


    @Override
    public void run() {
        try {
            System.out.println("client trying to connect after thread creation");

            ServerSocket server = new ServerSocket(8080);
            while (true) {

                SocketConnection client = new SocketConnection(server.accept(), clientInfo);
                client.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

更改您的SockectConnection以删除列表

           HashMap<String, ClientInfo> clientinfo;

            public SocketConnection(Socket socket, HashMap<String, ClientInfo> clientInfo) {
                super("Thread 1");

                this.socket = socket;
                //this.hm = dataHashMap;
                this.clientinfo = clientInfo;

                try {

    // IT IS PRINTING TOTAL SIZE 3 SUCCESSFULLY HERE
                    int totalClientList = clientInfo.size();
                    System.out.println("totalClientList: " + totalClientList);

                    if ( totalClientList>0 )
                    {


  // IT IS GETTING ONLY THE LAST KEY, OTHER KEYS ARE SHOWING EMPTY
                            Set<String> key = clientInfo.keySet()
                            Iterator it = key.iterator();

                            while (it.hasNext()) {
                                System.out.println("hasNexthasNext");
                                String hmKey = (String)it.next();
                                ClientInfo hmData = (ClientInfo) tmpData.get(hmKey);

                                System.out.println("Key: "+hmKey +" & Data: "+hmData.getRandomNo());
                                it.remove(); // avoids a ConcurrentModificationException
                            }

                        // TO ADD NEW CLIENT EVERY TIME
                        addNewClient();
                    }
                    else {
                        System.out.println("Client List shows empty");

                        // TO ADD NEW CLIENT EVERY TIME
                        addNewClient();
                    }

                    // Not used yet, will be used
                    input = socket.getInputStream();
                    scannerObj = new Scanner(socket.getInputStream());
                    clientOutput = socket.getOutputStream();


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

更改添加新客户:

    void addNewClient () {

        String ipAddress = getLocalIP();

        if ( ipAddress!=null )
        {
            ClientInfo clientobj = new ClientInfo();

            clientobj.setIPAdd(ipAddress);
            int randno =  genRandomNumber();
            System.out.println("genRandomNumber() : " + randno);
            clientobj.setRandomNo(randno);

            String key = String.valueOf(randno);

            clientinfo.put(key, clientobj);

        }
    }

我刚编辑了你的代码,它应该给你一个开始。希望这会有所帮助。

答案 2 :(得分:0)

你在谈论两件不同的事情。一个是列表的大小,另一个是hashMap的大小。 试试这个:

int mapSize = tmpData.size();

您可以获取地图的大小并检查它是否正确。