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!

2 Risposte
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
TECNICO DI SUPPORTO
Udit_P
con risposta un anno fa
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
ESPERTO
Uri
con risposta un anno fa
  • @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.

Accesso non effettuato. Accedi per postare una risposta.

Una buona risposta soddisfa chiaramente la domanda, fornisce un feedback costruttivo e incoraggia la crescita professionale del richiedente.

Linee guida per rispondere alle domande