Can you send a message to a websocket client from a non-websocket lambda?

佐手、 提交于 2020-05-30 07:35:12

问题


I have a nodejs websocket AWS lambda endpoint (Api Gateway) set up and it connects and can echo messages back. During initial connection, I save the endpoint and connection_id to a database. That gets saved just fine. If I open a browser client, and connect to the websocket endpoint, I can connect successfully, and send a message from the browser successfully - I have code to echo the message back, and it works.

Now, in another nodejs lambda, one that provides a REST endpoint, I have code that loads the connection_id from the database and does this:

// 'connection' is loaded successfully from DB (I log it and see the right values)
let api = new AWSSDK.ApiGatewayManagementApi({apiVersion: '2018-11-29', endpoint: connection.endpoint});

await api.postToConnection({
                ConnectionId: connection.connection_id,
                Data: JSON.stringify({ message: 'Hello World' })
            }).promise();

However, the code in the REST endpoint (code above) always gets a 410 error in the postToConnection. I know the connection is still active, since I can connect to it and ping it in a browser client just prior to testing the REST API above.

Is it not possible to post to a websocket connection from a non-websocket lambda?


回答1:


I think you should use this to send messages from the backend to your clients.

To send a callback message to the client, use:

POST https://{api-id}.execute-api.us-east-1.amazonaws.com/{stage}/@connections/{connection_id}

https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html



来源:https://stackoverflow.com/questions/57031348/can-you-send-a-message-to-a-websocket-client-from-a-non-websocket-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!