Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 243
Berry Avatar asked Feb 06 '23 20:02

Berry


2 Answers

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.

like image 128
kaqqao Avatar answered Feb 08 '23 12:02

kaqqao


There are 2 options :

1.)

Through a Web Service.

A Web service is a technology to communicate one programming language with another. For example, java programming language can interact with PHP and .Net by using web services. In other words, web service provides a way to achieve interoperability.

As you can see in the figure, Java, .Net or PHP applications can communicate with other applications through web service over the network. For example, java application can interact with Java, .Net and PHP applications (In this case, JavaScript).

So web service is a language independent way of communication.

You can send JSON through a web service called REST for example thanks to Jax-RS.

REST stands for REpresentational State Transfer. It is a type of a web service that is commonly preferred.

But you'll need to build a HTTP server, an application server (Jboss) or at least a servlet container (tomcat).

Then you'll be able to retrieve your JSON string with Ajax in a browser or curl like client with electron.

Read more about building Java Web Services here

2.)

Through a Java Core Program Socket Server

if you want to avoid JEE, you can build a java core programm socket server listening on an IP+port and request this server (and receive the Json string) from JavaScript thanks to npm package like raw-socket

like image 39
kevin ternet Avatar answered Feb 08 '23 11:02

kevin ternet