I'm creating a client-server application wherein the server or client sends strings using PrintStream and reads strings using BufferedReader/InputStreamReader. Eventually, I need to either send an object from the server to the client or vice versa using ObjectInputStream/ObjectOutputStream.
How do I switch from sending/receiving strings to sending/receiving objects? I am getting "invalid stream header: 7372000E".
Here are the stream portions of the client (I cut out all the exceptions for brevity):
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedReader fromServer;
PrintStream clientToServer;
try {
fromServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
clientToServer = new PrintStream(sock.getOutputStream());
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
return;
}
String username;
String opcode;
System.out.print(fromServer.readLine()); // MESSAGE 1
username = in.readLine();
clientToServer.println(username); // MESSAGE 2
System.out.println(fromServer.readLine()); // MESSAGE 3
if (!username.matches("[a-zA-Z]\\w+")) {
return;
}
opcode = fromServer.readLine(); // MESSAGE 4
If statement and file stuff for opcode1, then:
ObjectInputStream ois;
ObjectOutputStream oos;
UUID u = null;
ois = new ObjectInputStream(new FileInputStream(f));
u = (UUID) ois.readObject();
oos = new ObjectOutputStream(sock.getOutputStream());
oos.writeObject(u); // MESSAGE 5
Else statement and more file stuff for opcode2, then:
ObjectOutputStream oos;
ObjectInputStream ois;
UUID u;
ois = new ObjectInputStream(sock.getInputStream());
u = (UUID) ois.readObject(); // MESSAGE 5
System.out.println("UUID " + u.toString() + " received.");
oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(u);
System.out.println("UUID " + u.toString() + " written to file.");
The server does the following:
PrintStream output = new PrintStream(sock.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
output.println("Please enter your username: "); // MESSAGE 1
username = input.readLine(); // MESSAGE 2
output.println("Welcome back!"); // MESSAGE 3
output.println("opcode1") OR output.println("opcode2") // MESSAGE 4
opcode1 section:
ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
UUID local = (UUID) ois.readObject(); // MESSAGE 5
if (user.getUUID().equals(local))
output.println("Your UUID is valid."); // MESSAGE 6
opcode2 section:
ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
oos.writeObject(u.getUUID()); // MESSAGE 5
output.println("You now have a UUID."); // MESSAGE 6