简体   繁体   English

如何从AWS Lambda Node.js 8.10异步函数向AWS API网关返回net.socket数据?

[英]How to return net.socket data from AWS Lambda Node.js 8.10 async function to AWS API gateway?

I have this Lambda function: 我有这个Lambda函数:

exports.handler = async (event,context,callback) => {
  // console.log('Received event:', JSON.stringify(event, null, 2));
  var key=event.queryStringParameters.ref;
  // console.log('index.handler started with key : '+key);
  var RemoteServer='aaa.bbb.ccc.ddd';
  var net = require('net');
  var responce={
      "statusCode": 200,
      "headers": {
          "Content-Type": "*/*"
      }
  };

  var socket = new net.Socket();

  socket.setEncoding('utf8');

  socket.on('close', () => {
    console.log('Close.');
    console.log(JSON.stringify(responce));
    callback(null, JSON.stringify(responce));

  });
  socket.on('connect', () => {
    // console.log('Connect');
    var senddata='1,'+key;
    // console.log(('About to write :'+senddata));
    socket.write(senddata);
    console.log(('Wrote :'+senddata));
  });
  socket.on('data', (data) => {
    console.log('Data.');
    responce.body = data;
    console.log(JSON.stringify(responce));
    socket.end();
  });
  socket.on('end', () => {
    console.log('End.');
    console.log(JSON.stringify(responce));
  });
  socket.on('error', (error) => {
    console.log('Error' + error);
    socket.destroy;
    callback(error);
  });
  socket.on('timeout', () => {
    console.log('Timeout');
    socket.close;
    callback('Timeout');
  });

  socket.connect(11010, RemoteServer, () => { 
    // console.log('socket connect');
  });

  callback(null,responce); // This is here to get this to do anything.
};

It works, in as such that the console.log shows that I am getting the correct data in the socket.on('data') routine. 它的工作原理是,console.log显示我在socket.on('data')例程中获取了正确的数据。

However, it fails to return the responce.body in the callback. 但是,它无法在回调中返回responce.body。 Also, it only works if I have a callback in the async function, not in the event listeners. 同样,它仅在异步函数中有回调的情况下才起作用,而在事件侦听器中没有。

This is my output - console.log: 这是我的输出-console.log:

START RequestId: 7e1876fe-4255-12de-56d6-c187bcfff9ee Version: $LATEST
Wrote :1,R9H39X
Data.
{"statusCode":200,"headers":{"Content-Type":"*/*"},"body":"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<group>\r\n  <data>\r\n    <name>COLIN MANNING</name>\r\n    <from>26/03/2018</from>\r\n    <to>31/05/2018</to>\r\n    <room>A31</room>\r\n    <location>X,Y</location>\r\n  </data>\r\n</group>\r\n"}
End.
{"statusCode":200,"headers":{"Content-Type":"*/*"},"body":"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<group>\r\n  <data>\r\n    <name>COLIN MANNING</name>\r\n    <from>26/03/2018</from>\r\n    <to>31/05/2018</to>\r\n    <room>A31</room>\r\n    <location>X,Y</location>\r\n  </data>\r\n</group>\r\n"}
Close.
{"statusCode":200,"headers":{"Content-Type":"*/*"},"body":"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<group>\r\n  <data>\r\n    <name>COLIN MANNING</name>\r\n    <from>26/03/2018</from>\r\n    <to>31/05/2018</to>\r\n    <room>A31</room>\r\n    <location>X,Y</location>\r\n  </data>\r\n</group>\r\n"}
END RequestId: 7e1876fe-4255-12de-56d6-c187bcfff9ee
REPORT RequestId: 7e1876fe-4255-12de-56d6-c187bcfff9ee    Duration: 178.76 ms     Billed Duration: 200 ms Memory Size: 1536 MB    Max Memory Used: 33 MB 

and callback: 和回调:

{"statusCode":200,"headers":{"Content-Type":"*/*"}}

And this is the console.log without the last callback: 这是没有最后一个回调的console.log:

START RequestId: c3dc7e69-87aa-1608-76d4-093a0e28711b Version: $LATEST
END RequestId: c3dc7e69-87aa-1608-76d4-093a0e28711b
REPORT RequestId: c3dc7e69-87aa-1608-76d4-093a0e28711b    Duration: 3.43 ms       Billed Duration: 100 ms Memory Size: 1536 MB    Max Memory Used: 33 MB

and callback: 和回调:

null

So without the callback, nothing runs. 因此,如果没有回调,则什么也不会运行。

What I want to achieve is: Open socket to server. 我要实现的是:打开服务器套接字。 send data through socket get reply from server through socket close socket return reply to API Gateway 通过套接字发送数据从服务器通过套接字获取答复关闭套接字返回对API网关的答复

This is my first attempt at Node.js async, Lambda and API Gateway. 这是我第一次尝试使用Node.js异步,Lambda和API网关。 I assume that I have an error in the way I understand Node.js async and callbacks. 我假设我在理解Node.js异步和回调的方式上有错误。

How do I return the data from the socket.on('close') listener? 如何从socket.on('close')侦听器返回数据?

It appears to me that the callback in the listener is never called, I and cannot determine how to make the callback in the async function await for the data from the listener. 在我看来,侦听器中的回调从未被调用,我也无法确定如何使异步函数中的回调等待来自侦听器的数据。

Am I supposed to use EventAsPromise and then block with a while (!done) {....}? 我是否应该使用EventAsPromise然后在一段时间内(!done){....}进行阻止? This seams to go against the Node async philosophy. 这违反了Node异步哲学。

OK, so I found this post: 确定,所以我找到了这篇文章:

How Can I Wait In Node.js (Javascript), l need to pause for a period of time 我如何在Node.js(Javascript)中等待,我需要暂停一段时间

and went down to Aminadav's answer. 然后听了Aminadav的回答。

So I end up with this function declared ahead of my existing code: 因此,我最终在现有代码之前声明了此函数:

function sleep(ms){
    return new Promise(resolve=>{
        setTimeout(resolve,ms)
    })
};

and now the end of my original code looks like this: 现在我原始代码的结尾看起来像这样:

  socket.connect(11010, RemoteServer, () => {
    // console.log('socket connect');
  });

  while (!socket.destroyed) {
    await sleep(10);
  }

  callback(null,responce);
};

So now I get the data returned to my calling function. 现在,我将数据返回给调用函数。

I'm not sure that a sleep() is the best way to do this, but it gets me moving on. 我不确定sleep()是执行此操作的最佳方法,但它会让我继续前进。 This is an answer, but I appreciate that it may not be the best answer. 这是一个答案,但我知道这可能不是最佳答案。

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

相关问题 Node.js 8.10中具有异步瀑布的AWS Lambda查询 - AWS Lambda query with async waterfall in node.js 8.10 如何从AWS Lambda node.js异步函数返回数据? - How to return data from AWS Lambda node.js asynchronous function? 您是否可以使用由node.js 8.10支持的AWS Lambda函数将多个消息发布到SNS主题? - Can you publish multiple messages to an SNS topic using an AWS Lambda function backed by node.js 8.10? 处理程序函数中的AWS Lambda Node JS 8.10语法错误 - AWS Lambda Node JS 8.10 Syntax error in handler function 如何解析AWS Lambda(node.js)中通过AWS Api网关上传的数据的内容类型? - How to parse the Content-type of the data being uploaded through aws Api gateway in aws Lambda (node.js)? AWS Lambda Node运行时从Node.js v4.3更新到Node.js v8.10 - AWS Lambda Node runtime update from Node.js v4.3 to Node.js v8.10 使用 node.js 从 AWS Lambda 将自定义错误传回 AWS API Gateway - Passing custom errors back to AWS API Gateway from AWS Lambda using node.js AWS Lambda 与 API 网关和 Node.js 返回 HTTP 50 - AWS Lambda with API gateway and Node.js returning HTTP 502 如何将一系列数据包写入Node.js net.Socket? - how to write a sequence of packets to a Node.js net.Socket? 如何检测net.Socket连接是否死亡 - node.js - How to detect if net.Socket connection dies - node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM