0

I'm writing a program where the server draws a shape in its app and the client can see that shape in its own app. I thought about converting the object to a byte array but it didn't do anything.

The server code

private void sendShape(Graphics drawedShape) {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();        

        try {


              ObjectOutputStream oos = new ObjectOutputStream(bos);
              oos.writeObject(drawedShape);
              oos.flush();
              byte[] yourBytes = bos.toByteArray();
              /*oos.writeObject(drawedShape);
            oos.flush();
            dispMessage("\n Teacher:" + "Shape sent!");*/
        } catch (IOException e) {
            jta.append("\nError");

        }
    }

The client code

private void processConn() throws IOException {
        send("Successful");
        setButtonEnabled(true);
        String msg = "";
        Graphics object;
            ByteArrayInputStream bis = null;
        do {
            try                

            {
                   Object incomingObject = ois.readObject();

                   if(incomingObject.getClass().toString().contains("Graphics"))
                   {
                       try {
                       ois = new ObjectInputStream(bis);
                       Object o = ois.readObject(); 
                          /*object = (Graphics) ois.readObject();
                          dispMessage("\n" + object);*/
                       }finally {
                           try {
                                if (ois != null) {
                                  ois.close();
                                }
                              } catch (IOException ex) {

                              }
                         }
                   }
  • You cannot serialize and deserialize most of the Java objects this way. So the Object in your client will never be a Graphics-Object. Also the if-clause to check the class of the object is error-prone. You should use the instanceof keyword. You can also not send a Graphics-Object to a client because there are OS-dependant and instance-dependant parameters in the object. To send information about your graphics object you have the find to serialize and deserialize it (e.g. Draw everything to the graphics, create an image and sent this bytes, but this might not be what you expected) – jsc57x May 26 '20 at 19:04
  • See [How to serialize Java 2D Shape objects as XML?](https://stackoverflow.com/q/26579729/418556) – Andrew Thompson May 26 '20 at 22:02

0 Answers0