12
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Amazon API GatewayのWebsocketを試す

Posted at

はじめに

2018/12/19にAPI gatewayがwebsocketに対応したのでためしみてみます。

以下のサンプルになります。
https://github.com/aws-samples/simple-websockets-chat-app

作成する構成

image.png

クライアントからWebsocketで接続に行くと、onConnect関数が実行され、コネクションIDがDynamoDBに登録されます。
メッセージを添えてsendMessageアクションを実行すると、sendMessage関数がDynamoDBに保存されたコネクションIDに対して、メッセージを送信する。

手順

赤枠の構成をCloudFormationで作成

SAMで作成したcFnテンプレートがS3のバケットを準備しておきます。
git cloneしてSAM/cFn実行します。

git clone https://github.com/aws-samples/simple-websockets-chat-app.git
cd simple-websockets-chat-app
sam package --template-file template.yaml --output-template-file output.yaml --s3-bucket <S3バケット>
aws cloudformation deploy --template-file output.yaml --capabilities CAPABILITY_IAM --stack-name websocket-test

青枠のAPI Gatewayの構築

Create APIをクリックする。
image.png

WebSocketを選択する。
API Name: WebSocketと入力する。
Route Selection Expression:$request.body.action
Create APIをクリックする。
image.png

sendmessageルートを作成する。sendmessageと入力に右横のチェックマークをクリックする。
image.png

connectルートにonConnect関数を登録する。
Integration Requestをクリック。

image.png

Lambda FunctionにStack名-OnConnect-Functionxxxxを指定します。
image.png

上記を、disconnect/sendmessage/default分繰り返します。
defaultは、選択式がAPIルート内の他のrouteKeyに一致しない値を生成する場合に使用されます。今回は特にエラーハンドリング用の関数がないので、仮にonConnectを指定します。
何かしら紐づけておかないとAPIをデプロイするときにエラーになります。
image.png

APIをデプロイする。
image.png

APIデプロイ完了。
image.png

確認

NPMをインストールしてwscatをインストールする。

npm install -g wscat

メッセージ送信用と受信用のターミナルを開いてWebsocketで接続する

wscat -c wss://<API ID>.execute-api.<Region>.amazonaws.com/dev
connected (press CTRL+C to quit)
> 
> 

以下のJSONを入力する

{"action":"sendmessage", "data":"hello world"}

受信用のターミナルでメッセージが表示されることを確認する。

connected (press CTRL+C to quit)
< hello world
> 

お約束

投稿内容は私個人の意見であり、所属企業・部門見解を代表するものではありません。

12
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?