java socket,客户端的HashMap值没有改变

时间:2016-04-27 10:13:41

标签: java sockets

我正在测试游戏的聊天系统 它是聊天系统,但是客户端发送位置信息,如“2 3”,服务器进程信息并保存到ConcurrentHashMap,其中String类型名称为Key,User对象为Value。
用户对象具有String类型位置变量 第一次保存很好。之后,Server的HashMap更改了值,但Client的hashMap没有更改值 我听说HashMap不适合线程,需要同步。所以我使用了ConcurrentHashMap但它没有修复 为什么客户端的HashMap值没有改变? 请帮助我 以下是我的代码。

serverTest.java



    package SocketPractice2;

    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.concurrent.ConcurrentHashMap;

    import Model.User;

    public class serverTest {
        static ServerSocket server;
        static List clients;
        static ConcurrentHashMap strTable;
        static ConcurrentHashMap userTable;
        static int userId = 1111;

        serverTest() throws IOException {
            server = new ServerSocket(5000);
            clients = new ArrayList();
            strTable = new ConcurrentHashMap(); //
        }

        public static void main(String[] args) {
            try {
                new serverTest();
                Socket socket = null;
                userTable = new ConcurrentHashMap();
                while ((socket = server.accept()) != null) {
                    ConnectionToClient client = new ConnectionToClient(socket);
                    clients.add(client);
                    System.out.println("[Info] client connected");
                    String name = (String) client.read();
                    String initialLocation = "1 1";
                    User user = new User(name, initialLocation, false);
                    userTable.put(name, user);
                    new MessageHandler(client).start();
                }

                server.close();
            } catch (Exception e) {
                try {
                    Iterator itr = clients.iterator();
                    while (itr.hasNext()) {
                        itr.next().close();
                    }
                } catch (Exception g) {

                }
                e.printStackTrace();
            }
        }

        public static void tellEveryOne(Object message) {
            try {
                for (ConnectionToClient client : clients) {
                    client.write(message);
                }
            } catch (Exception e) {
            }
        }

        private static class MessageHandler extends Thread {
            ConnectionToClient client;

            MessageHandler(ConnectionToClient client) {
                this.client = client;
            }

            public void run() {
                try {
                    String input = "";
                    while ((input = (String) client.read()) != null) {
                        System.out.println("Read : " + input);
                        String[] nameAndLocation = input.split(":");
                        String name = nameAndLocation[0];
                        String Location = nameAndLocation[1];

                        // strTable.put(name, Location);
                        // tellEveryOne(strTable);
                        userTable.get(name).setLocation(Location);
                        System.out.println("changed : " + userTable.get(name).getLocation());
                        tellEveryOne(userTable);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        private static class ConnectionToClient {
            Socket socket;
            ObjectInputStream ois;
            ObjectOutputStream oos;

            ConnectionToClient(Socket socket) throws IOException {
                this.socket = socket;
                ois = new ObjectInputStream(socket.getInputStream());
                oos = new ObjectOutputStream(socket.getOutputStream());
            }

            public void write(Object message) throws Exception {
                oos.writeUnshared(message);
                oos.flush();
            }

            public Object read() throws Exception {
                return ois.readObject();
            }

            public void close() throws IOException {
                socket.close();
                ois.close();
                oos.close();
            }
        }
    }



clientTest.java



    package SocketPractice2;

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    import java.util.Map.Entry;
    import java.util.concurrent.ConcurrentHashMap;

    import Model.User;

    public class clientTest {
        static Socket socket;
        static final String ip = "127.0.0.1";
        static final int port = 5000;
        static String name;
        clientTest() {
            try {
                socket = new Socket(ip, port);
            } catch (Exception e) {
            }
        }

        public static void main(String[] args) {
            try {

                new clientTest();
                ConnectionToServer server = new ConnectionToServer(socket);

                new MessageHandler(server).start();

                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));

                String input = "";
                // login
                System.out.print("Input name : ");
                name = keyboard.readLine();
                server.write(name);
                System.out.println("[Info] Connection complete");
                while ((input = keyboard.readLine()) != null) {
                    server.write(name + ":" + input);
                }
                socket.close();

                keyboard.close();
            } catch (Exception e) {
                e.printStackTrace();

            }
        }

        private static class MessageHandler extends Thread {
            static ConnectionToServer server;

            MessageHandler(ConnectionToServer server) {
                this.server = server;
            }
            ConcurrentHashMap cHashMap;

            public void run() {
                ConcurrentHashMap strtable = new ConcurrentHashMap();
                ConcurrentHashMap usertable = new ConcurrentHashMap();
                try {
                    while((usertable = (ConcurrentHashMap)server.read())!=null){
                        for(Entry user : usertable.entrySet()){
                            String name = user.getKey();
                            String location = user.getValue().getLocation();
                            System.out.println(name + ":" + location);

                        }
                        usertable.clear();
                    }


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

        private static class ConnectionToServer {
            static Socket socket;
            static ObjectInputStream ois;
            static ObjectOutputStream oos;

            ConnectionToServer(Socket socket) {
                try {
                    this.socket = socket;
                    oos = new ObjectOutputStream(socket.getOutputStream());
                    ois = new ObjectInputStream(socket.getInputStream());

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

            public void write(Object message) throws Exception {
                oos.writeUnshared(message);
                oos.flush();
            }

            public Object read() throws Exception {
                return ois.readObject();
            }

            public void close() throws Exception {
                ois.close();
                oos.close();
            }

        }
    }




User.java



    package Model;

    import java.io.Serializable;

    public class User implements Serializable{
        /**
         * 
         */
        private static final long serialVersionUID = -505870546358096892L;
        /**
         * 
         */
        private int userId;
        private String userName;
        private int hp;
        private Location location;
        private boolean isZombie;
        private String strLocation;

        public User(String userName, String location, boolean isZombie){
            this.userName = userName;
            this.hp = 100;
            this.strLocation = location;
            this.isZombie = isZombie;
        }

        public User(int userId, String userName, Location location, boolean isZombie) {
            this.userId = userId;
            this.userName = userName;
            this.location = location;
            this.isZombie = isZombie;
        }



        public int getId(){return userId;}

        public String getUserName(){return userName;}

        public int getHP(){return hp;}
        public void setHP(int hp){this.hp = hp;} 

        public String getLocation(){return strLocation;}
        public void setLocation(String location){this.strLocation = location;}


        public String getLocationX(){return location.getLocationX();}
        public void setLocationX(String locationX){location.setLocationX(locationX);}
        public String getLocationY(){return location.getLocationY();}
        public void setLocationY(String locationY){location.setLocationY(locationY);}

        public boolean getisZombie(){return isZombie;}


    }


0 个答案:

没有答案