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개 답변
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
답변함 일 년 전
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
답변함 일 년 전
  • @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.

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠