Search code examples
javasocketsdistributed-computingobjectoutputstream

Sending Executable Java over a Socket


I'm working on a networking project in Java where I want to send some executable code from Node A to Node B and have Node B return the result of the executed code back to Node A.

The way I went about trying to do this (Which I now know isn't suitable for my use case) was to define an abstract class called Job which had an abstract method run(). It looks something like this:

import java.io.Serializable;

public abstract class Job implements Serializable {

  public String id;

  public Job(String id) {
      this.id = id;
  }

  public abstract void run();

}

I was then planning to be instantiate children classes from Job, defining the run method and to send the derived class from Node A to Node B using the built in ObjectOutputStream and ObjectInputStream and have simply have Node B call the run() method when it received a job.

However this goes beyond what can be done with a Serialized Object sent though the ObjectOutputStream as Node B would need the exact definition of the class being sent from Node A - which it can't have as each Job will be of a different sub type and will have different definitions of the run() method.

Does anyone know of any other way to do this? A way to send executable code from Node A to Node B and have Node B execute the code?

I know I could probably just create .jars and send them through the OutputStream, and have Node B execute them. But if there is any way I could do this with having a base Job class that I can extend and instantiate from to define different types of Jobs and send those Jobs to Node B?

Any help or suggestions would be greatly appreciated!! Thanks in advance! :)


Solution

  • You can do exactly this via RMI and the codebase feature.