在套接字上发送散列图 - 收到关于发送内容的不同变量

时间:2017-07-30 11:58:17

标签: java sockets networking scope global-variables

我正在尝试建立一个客户端服务器' chat'有房间,但我遇到了问题。当用户连接到服务器时,房间信息被发送到客户端,因此可以用现有房间填充适当的GUI元素。这完全有效,但是当客户端连接到服务器,并且使用服务器我创建一个新房间时,它应该将房间信息重新发送给客户端,这应该自动刷新GUI元素,但无论出于何种原因,都会发送正确的hashmap,但是在客户端中,它被接收为先前的房间变量,例如如果用户连接时没有房间存在,即使填充的hashmap被发送到客户端,它也只会收到一个空的hashmap。我相当肯定它与本地范围有关但我无法看到它;任何帮助表示赞赏。

服务器:

private HashMap<String, List<String>> rooms;
ServerSocket socket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
ServerUI(){}

HashMap<String, List<String>> getRooms() {
    return this.rooms;
}

void setRooms(HashMap<String, List<String>> setTo) {
    this.rooms = setTo;
}

void createRoomsVariable() {
    HashMap<String, List<String>> rooms = new HashMap<String,List<String>>();
    rooms.put("Default room", new ArrayList<String>());
    setRooms(rooms);
}

public static void main(String[] args) {
    ServerUI server = new ServerUI();
    server.ui();
    server.setVisible(true);
    server.createRoomsVariable();
    while(true) {
        server.run();
    }
}


void run() {
    try {
        //initialise
        socket = new ServerSocket(10015, 10);
        textArea.append(">>>Waiting for connection \n");
        connection = socket.accept();
        textArea.append(">>>Connection received from " + connection.getInetAddress().getHostName() + "\n");

        out = new ObjectOutputStream(connection.getOutputStream());
        out.flush();
        in = new ObjectInputStream(connection.getInputStream());
        //server sends message to let user know connection is established
        sendMessage("Connection successful");

        //send room info

        sendRoomInfo(getRooms());

        while (true) {
            try {
                //incoming message is read, it is the appended to the console then processed
                message = (String)in.readObject();

                textArea.append("client>" + message + "\n");
                if (message.equals("bye")) {
                    sendMessage("bye");
                    textArea.append(">>>Connection closed \n");
                    break;
                } else if(message.equals("!roominfo")) {
                    sendRoomInfo(getRooms());
                }
            } catch (ClassNotFoundException e) {
                System.err.println("Data received in unknown format");
            }
        }// while(!message.equals("bye"));

    } catch(IOException e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
            out.close();
            socket.close();

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

}
void sendRoomInfo(HashMap<String, List<String>> rooms) {
    try {
        textArea.append("I will send the following: " + rooms);
        sendMessage("Sending room info");
        out.writeObject(rooms);
        out.flush();
        sendMessage("Sent");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
void sendMessage(String msg) {
    try {
        out.writeObject(msg);
        out.flush();
        textArea.append("server>" + msg + "\n");
    } catch (IOException e) {
        e.printStackTrace();
    } 
}

void createRoom(HashMap<String, List<String>> rooms, String roomName) {

    List<String> users = new ArrayList<String>();
    rooms.put(roomName, users);
    setRooms(rooms);
}
public void ui() {
    //...ui stuff

    //actions
    sendBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            message = textField.getText();
            String[] splitMessage = message.split(" ");
            if (splitMessage[0].equals("!create")) {
                createRoom(getRooms(),splitMessage[1]);
                textArea.append(">>>Room created \n");
                textField.setText("");
                sendRoomInfo(getRooms());
            }
        }
    });
}

客户端

public static void main(String[] args) {
    ClientUI client = new ClientUI();
    client.ui();
    client.setVisible(true);
    client.run();
}

@SuppressWarnings("unchecked")
void run() {
    try{
        //connection and streams
        requestSocket = new Socket("localhost", 10015);
        System.out.println("Connected to localhost in port 10015");

        out = new ObjectOutputStream(requestSocket.getOutputStream());
        out.flush();
        in = new ObjectInputStream(requestSocket.getInputStream());

        sendMessage("Hi my server");
        while (true) {
            try {
                //read message, check if its a string; if it is, process it appropriately,
                //else its room info, so rooms has to be constructed
                message = in.readObject();
                if (message instanceof String) {
                    System.out.println("server>" + message.toString());
                    if (message.equals("bye")) {
                        break;
                    }
                    //message = "bye";
                    //sendMessage(message);
                } else {
                    System.out.println("Received data: " + message + "\n");
                    HashMap<String, List<String>> rooms = (HashMap<String, List<String>>) message;
                    redoRooms(rooms);
                }
            } catch(ClassNotFoundException e){
                System.err.println("data received in unknown format");
            }
        } //while(!message.toString().equals("bye"));

    } catch(UnknownHostException e){
        System.err.println("You are trying to connect to an unknown host!");
    } catch(IOException e){
        e.printStackTrace();
    } finally{
        //4: Closing connection
        try {
            in.close();
            out.close();
            requestSocket.close();
        } catch(IOException e){
            e.printStackTrace();
        }
    }
}

//send message to server
void sendMessage(String msg) {
    try {
        out.writeObject(msg);
        out.flush();
        System.out.println("client>" + msg);
    } catch(IOException e) {
        e.printStackTrace();
    }
}

//construct rooms
void redoRooms(HashMap<String, List<String>> rooms) {
    roomsArea.setText("");
    if (!rooms.isEmpty()) {
        for (Entry<String, List<String>> entry: rooms.entrySet()) {
            roomsArea.append(entry.getKey() + "\n");
        }
    }
}

0 个答案:

没有答案