ArrayList <String> size is not saved between server and client
I am writing a server / client application in Java. To receive messages and then print the general conversation dialog box, I add each message from the client to the ArrayList of Strings and then send the entire ArrayList back to the client to print it as an entire conversation.
My problem is that although I constantly add elements to the ArrayList on the server, whenever I send it to the client, the size does not change and only the first element is saved.
Server program:
public class ArrayListServer {
public static void main(String[] args) {
int port = 8000;
String me = "Server: ";
ArrayList<String> convo = new ArrayList<String>();
try {
ServerSocket server = new ServerSocket(port);
System.out.println("Waiting for connection...");
Socket client = server.accept();
System.out.println("Established connection.");
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
int i = 0;
// receive messages from client
while (true) {
String msgFromClient = (String)in.readObject();
convo.add(msgFromClient);
System.out.println(me + "size: " + convo.size());
out.writeObject(convo);
}
} catch (IOException ioex) {
System.out.println("IOException occurred.");
} catch (ClassNotFoundException cnfex) {
System.out.println("ClassNotFoundException occurred.");
}
}
}
Client program:
public class ArrayListClient {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
int port = 8000;
String me = "Client: ";
Scanner input = new Scanner(System.in);
ArrayList<String> convo = new ArrayList<String>();
try {
Socket client = new Socket("localhost", port);
ObjectOutputStream toServer = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream fromServer = new ObjectInputStream(client.getInputStream());
while (true) {
System.out.print("> ");
String msg = input.nextLine().trim();
toServer.writeObject(msg);
convo = (ArrayList<String>)fromServer.readObject();
System.out.println(me + "size: " + convo.size());
}
} catch (UnknownHostException uhex) {
System.out.println("UnknownHostException occurred.");
} catch (IOException ioex) {
System.out.println("IOException occurred.");
} catch (ClassNotFoundException cnfex) {
System.out.println("ClassNotFoundException occurred.");
}
}
}
When I start the server and client, my output is:
> hi
Client: size: 1
> hi
Client: size: 1
> hi
Client: size: 1
> hi
Client: size: 1
> hi
Client: size: 1
> hi
Client: size: 1
>
Server: Waiting for connection...
Server: Established connection.
Server: size: 1
Server: size: 2
Server: size: 3
Server: size: 4
Server: size: 5
Server: size: 6
, ArrayList<> String , , . , /, while , IOException .
?
+3