如何通过网络将String从Java发送到JavaScript? [英] How would one send a String from Java to JavaScript over a network?

查看:146
本文介绍了如何通过网络将String从Java发送到JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Java生成的JSON字符串,我需要将这个字符串发送到另一台计算机,它将通过JavaScript接收它(因为电子)。 JavaScript计算机可能很远,并将通过互联网与Java应用程序联系。



Java应用程序不是各种Web应用程序,它是一个简单的后端app。



我该怎么做?

解决方案

制作您的Java应用程序可以从外部访问,您需要以某种方式将其暴露给网络。有很多方法可以做到这一点,但可以说最简单的,至少是你最容易找到帮助的方法是将它暴露为可通过HTTP访问的Web应用程序。同样,有数百种方法可以做到这一点,你应该真正阅读用Java开发的web开发。



让我们说你现有的应用程序做这样的事情(我不知道它实际做了什么因为你没有提供任何信息):

 公共类JsonMaker {
public String getJson(...){
return{\hello \:\world \};
}
}



将其公开为网络应用



现在,我知道制作Java Web应用程序的最快方式,使用星火。这是一个微框架,几乎不需要任何努力。



所有你需要做的就是将它公开到网上:


  1. 声明对Spark的依赖(或下载jar并将其放在你的类路径上):



< blockquote>

 < 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);
返回新的JsonMaker()。getJson(。 ..);
});
}
}




  1. 将此应用程序作为普通的Java应用程序运行,您将有一台服务器在端口4567上侦听HTTP GET请求并向您提供JSON服务。打开浏览器并转到:



    http:// localhost: 4567 / json


你会得到 {你好: world} 返回。



现在,您的客户端(JavaScript)应用程序需要发出与您的浏览器相同的GET请求,它将会获得回复。



阅读 Spark文档看看如何读取路径/查询字符串参数等,这样你就可以参数化你的请求,并根据给定的值做出不同的反应。



TCP套接字



正如Kevin Ternet在回答中所说,你不妨直接在你的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客户端可以在端口9090上打开与服务器的TCP连接,并直接发送/接收消息。因为它处于更低的水平,你将不得不自己做更多的重物,所以这种方式不推荐



注释



您所提出的问题有无限选择,您的问题相当广泛而模糊。 Spark是一种快速而简单的方法,可以帮助您开始使用Web应用程序。 Kevin公平地指出了REST,这是你应该采用的策略。 JAX-RS是一种Java标准的REST方式,但您也可以使用Spark或任何其他非兼容框架来实现。你真的需要在这里阅读和学习很多。



为了在Java中使用JSON,你再次拥有无数的选项,杰克逊 GSON 是2个热门选择。


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?

解决方案

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.

这篇关于如何通过网络将String从Java发送到JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆