使用套接字将数据从node.js发送到Java [英] Sending data from node.js to Java using sockets

查看:98
本文介绍了使用套接字将数据从node.js发送到Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过套接字将数据从node.js发送到Java。
我搜索过但没有什么是真正有用的。我习惯了socket.io,但在这种情况下它看起来并不适合这个。似乎node.js的所有套接字扩展都不适合发送消息,而是听取消息并回答某些内容。

I'm trying to send data from node.js to Java through sockets. 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. 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.

我的Java应用程序基本上应该收到一些从node.js开始工作,完成工作并将一些结果发送回node.js。不,这项工作不能在node.js上完成,它必须由Java完成(实际上是Scala,但无论如何)。

My Java app basically should receive some work to do from node.js, do the work and send some result to node.js back. And no, the work cannot be done on node.js, it has to be done by Java (which actually is Scala but whatever).

你们中的任何人都知道如何我可以这样做吗?

Does anyone of you know how can I do something like this?

谢谢

推荐答案

你可以使用node.js中的build in socket来做类似的事情(在java和node.js中都非常简单,但你会明白这一点):

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) :

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:

var net = require('net');

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

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

client.end();

关于套接字的node.js文档的链接: http://nodejs.org/docs/latest/api/net.html

And the link to the node.js doc about sockets : http://nodejs.org/docs/latest/api/net.html

这篇关于使用套接字将数据从node.js发送到Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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