[AWS] WebSockets with API Gateway

Websocket is a bit different from HTTP, they work on top of a TCP connection.

User connects to API Gateway with some payload, Apigateway routing the request to different Lambda functions:

 

There are some special routes defined for websockets,

  • `$connect`: When user connect to API Gateway thought websocket
  • `$disconnet`:
  • `$defualt`: default one, when there is no matching route

 

API Gateway WebSocket URL

WebSocket API provides two URLs: WebSocket URL and Connection URL.

WebSocket URL:

  • Clinent use to connect to API
  • Allows clients to send message and receive notifications

Connection URL:

  • Send back message to client
  • Lambda function use it to send message
  • Requires a connection id to send a message to particular client

Connection id will be stored in DynamoDB table, a lambda function will read from it.

 

Connection URL supports the following operations:

  • POST: to send a message to a client
  • GET: to get the latest connection status
  • DELETE: to disconnect a client from API

Here is an example of how to react to WebSocket events using Serverless Framework:

ConnectHandler:
    handler: src/websocket/connect.handler
    events:
      - websocket:
          route: $connect

  DisconnectHandler:
    handler: src/websocket/disconnect.handler
    events:
      - websocket:
          route: $disconnect

Installing Tool

npm install wscat -g
wscat -c wss://52zeaf29d.exeute-api.eu-central-1.amazonaws.com/dev

 

posted @   Zhentiw  阅读(173)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-05-18 [DevOps] Set up and run a PostgreSQL instance locally with Docker Compose
2020-05-18 [RxJS] Loading Spinner with busyDelayMs & busyMinDurationMs api
2019-05-18 [Algorithm] Area of polygon
2017-05-18 [SCSS] Write Custom Functions with the SCSS @function Directive
2017-05-18 [SCSS] Loop Over Data with the SCSS @each Control Directive
2016-05-18 [PWA] 14. Loop cursor
2016-05-18 [PWA] 13. New db and object store
点击右上角即可分享
微信分享提示