简体   繁体   English

使用 sockets 将数据从 node.js 发送到 Java

[英]Sending data from node.js to Java using sockets

I'm trying to send data from node.js to Java through sockets.我正在尝试通过 sockets 将数据从 node.js 发送到 Java。 I searched around but nothing was really useful.我四处寻找,但没有什么真正有用的。 I'm used to socket.io but in this case it doesn't seem really suitable for this.我习惯了 socket.io 但在这种情况下它似乎并不适合这个。 It seems like all the socket extensions for node.js are not really suited for sending messages, but rather listening to messages and answering something.似乎 node.js 的所有套接字扩展并不真正适合发送消息,而是听消息和回答某些东西。

My Java app basically should receive some work to do from node.js, do the work and send some result to node.js back.我的 Java 应用程序基本上应该从 node.js 接收一些工作,完成工作并将一些结果发送回 node.js。 And no, the work cannot be done on node.js, it has to be done by Java (which actually is Scala but whatever).不,这项工作不能在 node.js 上完成,它必须由 Java 完成(实际上是 Scala 等等)。

Does anyone of you know how can I do something like this?你们有谁知道我该怎么做这样的事情?

Thanks谢谢

You can use the build in socket in node.js to do something like that (very easy both in java and node.js, but you'll get the point) : 您可以使用node.js中的build in socket来执行类似的操作(在java和node.js中都非常简单,但您会明白这一点):

Java : Java:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Test {

    public static void main(String[] args) {
        ServerSocket server;
        Socket client;
        InputStream input;

        try {
            server = new ServerSocket(1010);
            client = server.accept();

            input = client.getInputStream();
            String inputString = Test.inputStreamAsString(input);

            System.out.println(inputString);

            client.close();
            server.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String inputStreamAsString(InputStream stream) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }

        br.close();
        return sb.toString();
    }

}

Node.js : Node.js:

var net = require('net');

var client = net.connect(1010, 'localhost');

client.write('Hello from node.js');

client.end();

And the link to the node.js doc about sockets : http://nodejs.org/docs/latest/api/net.html 以及有关套接字的node.js doc的链接: http//nodejs.org/docs/latest/api/net.html

you can use socket io this is a docs in link https://socket.io/您可以使用套接字 io 这是链接https://socket.io/中的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM