Berry Berry - 29 days ago 7
Java Question

How would one send a String from Java to JavaScript over a network?

I have a JSON String generated in Java, and I need to send this String to another computer, which will be receiving it through JavaScript (because electron). The JavaScript computer could be far away, and will contact the Java app through the internet.

The Java app is not a web app of sorts, it is a simple back end app.

How would I do this?

Answer

To make your Java application reachable from outside, you need to somehow expose it to the network. There quite a few ways to do this, but arguably the simplest and at least the one that you'll find help for the easiest is to expose it as a web app reachable through HTTP. Again, there's literally hundreds of ways to do this, and you should really read up on web development in Java.

Let's say your existing app does something like this (I have no clue what it actually does as you didn't give any info):

public class JsonMaker {
    public String getJson( ... ) {
        return "{\"hello\" : \"world\"}";
    }
}

Expose it as a web app

Now, the fastest way I know to make a Java web app, it using Spark. It's a micro-framework and requires almost no effort.

All you need to do to expose this to the web is:

  1. Declare a dependency to Spark (or download the jar and put it on your classpath):
<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.5</version>
</dependency>
  1. Make a simple server listening to HTTP calls and responding to them with your JSON:

import static spark.Spark.*;

public class SimpleServer {
    public static void main(String[] args) {
        get("/json", (req, res) -> {
            res.type("application/json");
            return new JsonMaker().getJson( ... );
        });
    }
}
  1. Run this app as a normal Java app, and you'll have a server listening on port 4567 for HTTP GET requests and serving your JSON to them. Open a browser and go to:

    http://localhost:4567/json

And you'll get {"hello": "world"} back.

Now, your client (JavaScript) app needs to make the same GET request your browser did, and it will get the response.

Read Spark documentation to see how to read path/query string parameters etc, so you can parameterize your requests and react differently depending on the given values.

TCP socket

As Kevin Ternet noted in his answer, you might as well listen on a socket directly in your Java app:

public static void main(String[] args) throws IOException {
    ServerSocket listener = new ServerSocket(9090);
    try {
        while (true) {
            Socket socket = listener.accept();
            try {
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                out.println(new JsonMaker().getJson( ... ));
            } finally {
                socket.close();
            }
        }
    }
    finally {
        listener.close();
    }
}

With this, your client and server will talk over TCP directly, instead over a defined protocol (like HTTP). Your JavaScript client can open TCP connections to your server on port 9090 and send/receive messages directly. Because it is at a much lower level, you'll have to do a lot more heavy lifting yourself, so this way is not recommended.

Notes

There's infinite options for what you're asking and your question is rather broad and vague. Spark is just a fast and simple way to get you started with web apps. Kevin fairly pointed out REST, and it's a strategy you should probably adopt. JAX-RS is a Java standard way of doing REST, but you can also do it with Spark or any other non-complient framework. You really need to read and learn a lot here.

For working with JSON in Java you have myriads of options again, Jackson and GSON being 2 popular choices.

Comments