Is it possible to use Socket.io with AWS Lambda?

后端 未结 8 1652
深忆病人
深忆病人 2021-01-30 01:31

Is it possible to build a function in AWS Lambda that creates a websocket and send data to subscribed applications?

Something like this:

John has the app SuperPh

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-30 02:03

    Yes, you can publish events as a socket.io client to a socket.io server using AWS Lambda.

    Steps to implement:

    • Create a node app locally, and execute npm install socket.io-client --save in the project folder.
    • Implement the handler code in index.js. Here is an example:
    exports.handler = async (event) => {
      var io = require('socket.io-client');
      var socket = io.connect("http://example.com:9999");
      let payload = { "id": "1" };
      socket.emit("MyEvent", payload);
      return 'Sent message!';
    };
    
    • Create a zip file of the folder.
    • In AWS Lambda, Select Upload a .Zip file
    • Ensure that after the files are uploaded that the file structure looks similar to:

    Project

    • node_modules
    • index.json
    • package-lock.json
    • package.json

    Save and test.

提交回复
热议问题