1

Im trying to make a client server 'chat' with rooms, but I'm encountering a problem. When the user connects to the server, room information is sent to the client so the appropriate GUI element can be filled in with the existing rooms. That works perfectly but while a client is connected to the server, and using the server i create a new room, it should resend the room information to clients which should automatically refresh the GUI element, but for whatever reason the correct hashmap is sent, but in the client it is received as the previous rooms variable, e.g. if there was no rooms existing when the user connected, it will just receive an empty hashmap even though a filled hashmap was sent to the client. I'm fairly sure it's something to do with local scope but I just can't see it; any help is appreciated.

Server:

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());
            }
        }
    });
}

Client

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");
        }
    }
}
peterxz
  • 864
  • 1
  • 6
  • 23

0 Answers0