websocket.py: Main program source filelambda_util.py: Utility functions to manage AWS Lambda functionswebsocket_connect.py: AWS Lambda function to implement the WebSocket$connectroutewebsocket_disconnect.py: AWS Lambda function to implement the WebSocket$disconnectroutewebsocket_send_msg.py: AWS Lambda function to implement the WebSocketsendmsgcustom route (Python)websocket_send_msg.js: AWS Lambda function to implement the WebSocketsendmsgcustom route (JavaScript)
- API Gateway WebSocket API
- AWS Lambda functions for the WebSocket
$connectand$disconnectroutes and a WebSocketsendmsgcustom route - AWS Identity and Access Management (IAM) role and policy for the AWS Lambda functions
- Amazon DynamoDB table to store connection IDs and user names
- Install Python 3.x.
- Install the AWS SDK for Python
boto3. Instructions are at https://github.com/boto/boto3. - Install the AWS CLI (Command Line Interface). Instructions are at https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html.
- Configure the AWS CLI. Instructions are at https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html.
To create the WebSocket infrastructure:
python websocket.py To delete the WebSocket infrastructure:
python websocket.py -d OR python websocket.py --delete To use the WebSocket Chat Program:
-
Download and install
Node.jsfrom https://nodejs.org.Node.jsincludes thenpmpackage manager. -
Use
npmto globally installwscat.npm install -g wscat -
When the WebSocket infrastructure is created, the WebSocket WSS address is output. Copy the output WebSocket WSS address and enter it on the
wscatcommand line to open a WebSocket connection. Open multiple connections by runningwscatin separate terminal windows.wscat -c WSS_ADDRESSExample command line:
wscat -c wss://123abc456def.execute-api.us-west-2.amazonaws.com/devOptional: Specify a user name as a query parameter in the WSS address (Used by the Python version of
websocket_send_msg.py)wscat -c wss://123abc456def.execute-api.us-west-2.amazonaws.com/dev?name=Steven -
Send a chat message to all open connections:
{"action": "sendmsg", "msg": "Enter message text here"}The
"action": "sendmsg"pair invokes the WebSocketsendmsgcustom route.The
"msg": "Enter message text here"pair specifies the message text to send. -
To close the WebSocket connection:
<Ctrl-C>