0

When I want to send Color object ovear socket, the method writeObject does not work. ...

public class Server {
public static void main(String[] args) throws IOException, InterruptedException {
    ServerSocket listener = new ServerSocket(9090);
    while (true) {
        Socket socket = listener.accept();
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        out.writeObject(Color.red);
        out.writeObject(Color.red);
        out.writeObject(Color.red);
    }
}
}

...

public class Client {
public static void main(String[] args) throws IOException, ClassNotFoundException {
    Socket socket = new Socket("", 9090);
    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
    System.out.println(in.readObject());
    System.out.println(Color.red == in.readObject());
    System.out.println(new Color(255, 0, 0) == in.readObject());
}
}

output:

java.awt.Color[r=255,g=0,b=0]
false //the output must be true
false //thre output must be true
hy240
  • 1
  • 2
  • Why _output must be true_? – Sotirios Delimanolis Jun 23 '16 at 15:52
  • Color.red == in.readObject()); try Color.red.equals(in.readObject()); – ControlAltDel Jun 23 '16 at 15:53
  • The Color.red.equals(in.readObject()) is correct, but I want to use in.readObject as a parameter for a method, it does not work – hy240 Jun 23 '16 at 15:59
  • Of course Color.red != in.readObject(), since the object is being serialized and sent of the network. Color objects DO NOT need to be from one of the final fields in Color, since colors are just rgb values, and the ones represented by fields in the Color class are just often-used colors. If a.equals(b), the two colors should behave the same. Have you actually tried putting the color in a method? And if so, what is the result? – Socratic Phoenix Jun 23 '16 at 16:23

0 Answers0