How to send String from Java to JavaScript over the network?

I have a JSON string generated in Java and I need to send this string to another computer that will receive it via JavaScript (because electron ). The JavaScript computer can be removed and it will contact the Java application over the Internet.

The Java application is not a web application, it is a simple back end application.

How should I do it?

+4
source share
2 answers

To make your Java application accessible from the outside, you need to somehow expose it on the network. There are quite a few ways to do this, but perhaps the easiest and at least the one that will help you the most is to expose it as a web application accessible via HTTP. Again, there are literally hundreds of ways to do this, and you should really read web development in Java.

Let's say your existing application does something like this (I don’t know what it actually does, since you did not give any information):

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

Open it as a web application

Now, the fastest way I know is to make a Java web application using Spark . It is a micro-frame and requires almost no effort.

All you have to do to open it online is:

  • Spark ( ):
<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.5</version>
</dependency>
  1. , HTTP 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. Java-, , 4567 HTTP GET JSON. :

    http://localhost:4567/json

{"hello": "world"} .

(JavaScript) GET, , .

Spark, , / .., - .

TCP

, Java:

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();
    }
}

TCP, (, HTTP). JavaScript TCP- 9090 / . , , .

, , . Spark - -. REST, , , , . JAX-RS Java REST, Spark . .

JSON Java , Jackson GSON 2 .

+4

2 :

1).

-.

A - - . , Java- PHP .Net -. , - .

, Java,.NET PHP - . , Java- Java,.Net PHP- ( JavaScript).

, - - .

JSON - REST, , Jax-RS.

REST REpresentational State Transfer. -, .

HTTP-, (Jboss) (tomcat).

JSON Ajax , .

Java-

2.)

Java

JEE, Java- Java, IP +, ( Json) JavaScript npm, raw-socket

+3

Source: https://habr.com/ru/post/1658804/


All Articles