gpt4 book ai didi

java - HTTP Node.js Java API

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:27:08 26 4
gpt4 key购买 nike

我正在创建一个 Node.js Java 后端。 Node.js 中间件从 Android 应用程序接收 HTTP 请求,然后将其转发给 Java 代码。选择此技术的原因是要从头开始创建高度可扩展的后端。

我希望 Node.js api 接收 HTTP 请求,将其传递到后端的 Java 端,Java 代码进行计算,将结果发送回 Node.js API,然后通过将结果发送回 Android 应用程序。

我可以接收和解析 HTTP 请求:

var BodyParser = require('body-parser');
var Express = require('express');
var JavaClient = require('./NodeJavaBridge.js');

var JavaClientInstance = new JavaClient();
var app = Express();

///// Receive message logic \\\\\
app.use(BodyParser.json());

app.post('/', function (request, response)
{
var task = request.body;

response.writeHead(200, { 'content-type': 'text/plain' });

var otherObject = { SomeData: 1234 };
var json = JSON.stringify({
data: otherObject
});

response.end(json);
});

console.log("START --> Java Client Instance");
JavaClientInstance.run();

app.listen(8080); //to port on which the express server listen
console.log("Server listening on: " + 8080);

我还可以在 Node.js 和 Java 之间发送和接收数据:

var Util = require('util');
var EventEmitter = require('events').EventEmitter;
var ChildProc = require('child_process');

var JavaClient = function () {
var _self = this;

// The child process object we get when we spawn the java process
var _javaSpawn = null;

// buffer for receiving messages in part and piecing them together later
var _receiveBuffer = null;

// The location of java and the - we're making these public because maybe
// we want to change them in the user of this module.
_self.javaPath = 'java';
_self.jarPath = 'C:/Dev/Backend_Java.jar';
_self.verbose = true;

// list of events emitted - for informational purposes
_self.events = [
'spawn', 'message', 'exception', 'unknown', 'sent', 'java_error',

// Response messages that then become events themselves
'Error', 'Hello', 'Info'
];

/**
* Attach our own event handler to reply to the hello message.
* This is just a convenience part of the protocol so that clients don't have to do it.
* Also connects if connection data was supplied.
*/
_self.on('Hello', function () {
_self.sendHello();
});

/**
* Executes the java process to begin sending and receiving communication
*/
_self.run = function () {
// Invoke the process
_javaSpawn = ChildProc.spawn(_self.javaPath, ['-jar', _self.jarPath]);

// Wire up events
_javaSpawn.stdout.on('data', onData);
_javaSpawn.stderr.on('data', onJavaError);
_javaSpawn.on('exit', function (code) {
console.log("The java program exited with code " + code + ".");
});

// Emit our own event to indicate to others that we have spawned
_self.emit('spawn', _javaSpawn);
}

// sends the hello request message
_self.sendHello = function () {
sendMessage(
{
messageName : 'Hello',
version : '1.1'
});
}

// sends a message that will be echoed back as an Info message
_self.sendEcho = function (message) {
sendMessage(
{
messageName : "Echo",
message : message
});
}

// sends a message telling the java app to exit
_self.sendGoodbye = function () {
sendMessage(
{
"messageName" : "Goodbye"
});
}

/**
* Sends a message object as a JSON encoded string to the java application for processing.
*/
function sendMessage(aMsg)
{
// convert to json and prepare buffer
var aJsonString = JSON.stringify(aMsg);
var lByteLength = Buffer.byteLength(aJsonString);
var lMsgBuffer = new Buffer(4 + lByteLength);

// Write 4-byte length, followed by json, to buffer
lMsgBuffer.writeUInt32BE(lByteLength, 0);
lMsgBuffer.write(aJsonString, 4, aJsonString.length, 'utf8');

// send buffer to standard input on the java application
_javaSpawn.stdin.write(lMsgBuffer);

_self.emit('sent', aMsg);
}

/**
* Receive data over standard input
*/
function onData(data)
{

// Attach or extend receive buffer
_receiveBuffer = (null == _receiveBuffer) ? data : Buffer.concat([_receiveBuffer, data]);

// Pop all messages until the buffer is exhausted
while (null != _receiveBuffer && _receiveBuffer.length > 3)
{
var size = _receiveBuffer.readInt32BE(0);

// Early exit processing if we don't have enough data yet
if ((size + 4) > _receiveBuffer.length)
{
break;
}

// Pull out the message
var json = _receiveBuffer.toString('utf8', 4, (size + 4));

// Resize the receive buffer
_receiveBuffer = ((size + 4) == _receiveBuffer.length) ? null : _receiveBuffer.slice((size + 4));

// Parse the message as a JSON object
try
{
var msgObj = JSON.parse(json);

// emit the generic message received event
_self.emit('message', msgObj);

// emit an object-type specific event
if ((typeof msgObj.messageName) == 'undefined')
{
_self.emit('unknown', msgObj);
}
else
{
_self.emit(msgObj.messageName, msgObj);
}
}
catch (ex)
{
_self.emit('exception', ex);
}
}
}

/**
* Receive error output from the java process
*/
function onJavaError(data)
{
_self.emit('java_error', data.toString());
}
}

// Make our JavaClient class an EventEmitter
Util.inherits(JavaClient, EventEmitter);

// export our class
module.exports = JavaClient;

我的问题:如何让 POST 请求向我的 JavaClient 实例发送请求,等待响应然后将其发送回原点(Android 应用程序)。

这是我如何尝试使逻辑正常工作的示例:

var client = require('./JavaClient');

var instance = new client();

instance.on('message', function(msg) {
console.log('Received a message...');
console.log(msg);
});

instance.on('sent', function(msg) {
console.log('Sent a message...');
console.log(msg);
});

instance.on('Info', function(msg) {
console.log("Received info");
console.log(msg.message);
});

(function() {
// Start it up (Hello exchanges happen)
instance.run();

// Receive acknowledgement of hello
instance.once('Info', function() {
// Try echoing something
instance.sendEcho("ECHO!");
});

})();

如果我应该说得更清楚,请告诉我(真的很晚了,我想我的写作能力正在下降)。我将不胜感激任何回答/建议/thisisabadidea 类型的评论。

谢谢!

最佳答案

var Util = require('util');
var EventEmitter = require('events').EventEmitter;
var ChildProc = require('child_process');

var JavaClient = function () {
var _self = this;

// The child process object we get when we spawn the java process
var _javaSpawn = null;

// buffer for receiving messages in part and piecing them together later
var _receiveBuffer = null;

// The location of java and the - we're making these public because maybe
// we want to change them in the user of this module.
_self.javaPath = 'java';
_self.jarPath = 'C:/Dev/Backend_Java.jar';
_self.verbose = true;

// list of events emitted - for informational purposes
_self.events = [
'spawn', 'message', 'exception', 'unknown', 'sent', 'java_error',

// Response messages that then become events themselves
'Error', 'Hello', 'Info'
];

/**
* Attach our own event handler to reply to the hello message.
* This is just a convenience part of the protocol so that clients don't have to do it.
* Also connects if connection data was supplied.
*/
_self.on('Hello', function () {
_self.sendHello();
});

/**
* Executes the java process to begin sending and receiving communication
*/
_self.run = function () {
// Invoke the process
_javaSpawn = ChildProc.spawn(_self.javaPath, ['-jar', _self.jarPath]);

// Wire up events
_javaSpawn.stdout.on('data', onData);
_javaSpawn.stderr.on('data', onJavaError);
_javaSpawn.on('exit', function (code) {
console.log("The java program exited with code " + code + ".");
});

// Emit our own event to indicate to others that we have spawned
_self.emit('spawn', _javaSpawn);
}

// sends the hello request message
_self.sendHello = function () {
sendMessage(
{
messageName : 'Hello',
version : '1.1'
});
}

// sends a message that will be echoed back as an Info message
_self.sendEcho = function (message) {
sendMessage(
{
messageName : "Echo",
message : message
});
}

// sends a message telling the java app to exit
_self.sendGoodbye = function () {
sendMessage(
{
"messageName" : "Goodbye"
});
}

/**
* Sends a message object as a JSON encoded string to the java application for processing.
*/
function sendMessage(aMsg)
{
// convert to json and prepare buffer
var aJsonString = JSON.stringify(aMsg);
var lByteLength = Buffer.byteLength(aJsonString);
var lMsgBuffer = new Buffer(4 + lByteLength);

// Write 4-byte length, followed by json, to buffer
lMsgBuffer.writeUInt32BE(lByteLength, 0);
lMsgBuffer.write(aJsonString, 4, aJsonString.length, 'utf8');

// send buffer to standard input on the java application
_javaSpawn.stdin.write(lMsgBuffer);

_self.emit('sent', aMsg);
}

/**
* Receive data over standard input
*/
function onData(data)
{

// Attach or extend receive buffer
_receiveBuffer = (null == _receiveBuffer) ? data : Buffer.concat([_receiveBuffer, data]);

// Pop all messages until the buffer is exhausted
while (null != _receiveBuffer && _receiveBuffer.length > 3)
{
var size = _receiveBuffer.readInt32BE(0);

// Early exit processing if we don't have enough data yet
if ((size + 4) > _receiveBuffer.length)
{
break;
}

// Pull out the message
var json = _receiveBuffer.toString('utf8', 4, (size + 4));

// Resize the receive buffer
_receiveBuffer = ((size + 4) == _receiveBuffer.length) ? null : _receiveBuffer.slice((size + 4));

// Parse the message as a JSON object
try
{
var msgObj = JSON.parse(json);

// emit the generic message received event
_self.emit('message', msgObj);

// emit an object-type specific event
if ((typeof msgObj.messageName) == 'undefined')
{
_self.emit('unknown', msgObj);
}
else
{
_self.emit(msgObj.messageName, msgObj);
}
}
catch (ex)
{
_self.emit('exception', ex);
}
}
}

/**
* Receive error output from the java process
*/
function onJavaError(data)
{
_self.emit('java_error', data.toString());
}
}

// Make our JavaClient class an EventEmitter
Util.inherits(JavaClient, EventEmitter);

// export our class
module.exports = JavaClient;

关于java - HTTP Node.js Java API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923974/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com