[英]Combining Java and Node.js through Sockets
I have the following Node.js code: 我有以下Node.js代码:
var http = require('http');
http.createServer(function(req, res)) {
console.log("URL request"+req.url);
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello World\n');
}).listen(9898, '127.0.0.1');
console.log('Server locally running at http://127.0.0.1:9898/');
I am using the Socket class in Java to make a socket that also connects to port 9898. I want whatever the Node.js writes (in this case 'Hello World'), to be processed by a Java class. 我正在使用Java中的Socket类制作一个也连接到端口9898的套接字。我希望Node.js编写的任何内容(在本例中为“ Hello World”)都由Java类处理。 So far, this is what I have for the Java class:
到目前为止,这是我为Java类准备的:
Socket s = new Socket(serverAddress, 9898);
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
My question is how do I get the 'Hello World' to be read by the Java code, so that whenever I call System.out.println(input.readLine())
, it prints 'Hello World'? 我的问题是如何获取Java代码读取的“ Hello World”,以便每当我调用
System.out.println(input.readLine())
,它都会显示“ Hello World”?
you had an extra ')' on the third line, but your code seems to otherwise work: 您在第三行上有一个额外的')',但是您的代码似乎可以正常工作:
var http = require('http');
http.createServer(function(req, res) {
console.log("URL request"+req.url);
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello World\n');
}).listen(9898, '127.0.0.1');
console.log('Server locally running at http://127.0.0.1:9898/');
i guess you need to create some java functionality to make a http request to the url:port the node server is running on. 我想您需要创建一些Java功能来向运行节点服务器的url:port发出http请求。 it probably wont be as simple as 'input.readLine()'.
它可能不会像“ input.readLine()”那样简单。
maybe something like this will help for getting the java code to get the data from node: 也许这样的事情将有助于获取Java代码以从节点获取数据:
How can I get an http response body as a string in Java? 如何在Java中将http响应正文作为字符串获取?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.