WebsocketApi Lambda and connect ECONNREFUSED

0

Hello, I've been setting up Websocket API with Lambda and I received following error:

<message-id>	INFO	Error: connect ECONNREFUSED <ip>
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: <ip>,
  port: 80,
  '$metadata': { attempts: 1, totalRetryDelay: 0 }

Env is a Node18 and Postman (ws) as a client.

Lambda's code:

import { ApiGatewayManagementApiClient, DeleteConnectionCommand,PostToConnectionCommand } from "@aws-sdk/client-apigatewaymanagementapi";

const api = new ApiGatewayManagementApiClient({endpoint: 'wss://<id>.execute-api.<region>.amazonaws.com/production',
    region: 'eu-central-1'
})


export const handler = async (event) => {
    
    
    console.log(event);
    
    const {routeKey, connectionId} = event?.requestContext
    let msg;
    
    console.log(`Request key is ${routeKey} and connectionID is ${connectionId}`)
    
    switch(routeKey){
        case '$connect':
            msg = 'connected My friend';
            break;
            
        case '$disconnect':
            msg = 'disconnected my friend';
            break;
            
        case 'message':
            try{
                await replyToMessage(connectionId, 'RAMP PAM PAM')
            }catch(e){
                console.log('EXEPTION ALARM')
                console.log(e)
            }
            break;
            
        default:
            console.log('something bad happened', routeKey);
            break;
    }
    
    // TODO implement
    const response = {
        statusCode: 200
    };
    
    
    return response;
};

const replyToMessage = (ConnectionId, message) =>{
        const data = {message};
        const cmd = new PostToConnectionCommand({
            ConnectionId,
            Data: Buffer.from(JSON.stringify(data))
        })
        
        const result =  api.send(cmd);
        console.log(result)
        return result;
    }

Lambda's policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "execute-api:*",
            "Resource": "arn:aws:execute-api:<region><id>:<api-id>/production/*"
        }
    ]
}

Thank you in advance, Arczik!

Arczik
已提問 1 年前檢視次數 1096 次
2 個答案
1

The endpoint used in replyToMessage in provided code snippet has 'wss' prefix, which means it is a websocket endpoint. To send a message to a connected client using 'ConnectionId' of the client, 'connections' endpoint needs to be used which has 'https' protocol. Updating the endpoint protocol 'wss' as in the following snippet to 'https' may help.

const api = new ApiGatewayManagementApiClient({endpoint: 'wss://<id>.execute-api.<region>.amazonaws.com/production',
    region: 'eu-central-1'
})

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

AWS
支援工程師
Udit_P
已回答 1 年前
0

I think you getting this error on the client side. Is it correct? The error indicates that you are trying to connect over port 80. API Gateway only supports port 443 using wss: protocol. I am guessing this is the reason for the error.

profile pictureAWS
專家
Uri
已回答 1 年前
  • @Uri thank you for your answer. In Postman I have a 'wss:/'/ prefix before api url. I get above mentioned error in 'replyToMessage' when I try to send message back to client.

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南