

# ステップ 4: 最初のメッセージを送受信する
<a name="getting-started-chat-send-and-receive"></a>

チャットトークンを使用してチャットルームに接続し、最初のメッセージを送信します。サンプルの JavaScript コードを以下に示します。IVS クライアント SDK も利用可能です。「[チャット SDK: Android ガイド](chat-sdk-android.md)」、「[ チャット SDK: iOS ガイド](chat-sdk-ios.md)」、「[チャット SDK: JavaScript ガイド](chat-sdk-js.md)」をご覧ください。

**リージョンサービス:** 以下のサンプルコードは、お客様の「サポート対象リージョン」を示しています。Amazon IVS Chat では、リクエストの実行に使用できるリージョンのエンドポイントを提供しています。Amazon IVS Chat メッセージング API の場合、リージョンエンドポイントの一般的な構文は次のとおりです。
+ wss://edge.ivschat.<region-code>.amazonaws.com

例えば、米国西部 (オレゴン) リージョンのエンドポイントは wss://edge.ivschat.us-west-2.amazonaws.com です。サポートされているリージョンのリストについては、「*AWS 全般のリファレンス*」の [Amazon IVS ページ](https://docs.aws.amazon.com/general/latest/gr/ivs.html)にある Amazon IVS Chat 情報を参照してください。

```
/*
1. To connect to a chat room, you need to create a Secure-WebSocket connection
using the client token you created in the previous steps. Use one of the provided 
endpoints in the Chat Messaging API, depending on your AWS region.
*/
const chatClientToken = "GENERATED_CHAT_CLIENT_TOKEN_HERE";
const socket = "wss://edge.ivschat.us-west-2.amazonaws.com"; // Replace “us-west-2” with supported region of choice.
const connection = new WebSocket(socket, chatClientToken);

/*
2. You can send your first message by listening to user input 
in the UI and sending messages to the WebSocket connection.
*/
const payload = {
  "Action": "SEND_MESSAGE",
  "RequestId": "OPTIONAL_ID_YOU_CAN_SPECIFY_TO_TRACK_THE_REQUEST",
  "Content": "text message",
  "Attributes": {
    "CustomMetadata": "test metadata"
  }
}
connection.send(JSON.stringify(payload));

/*
3. To listen to incoming chat messages from this WebSocket connection 
and display them in your UI, you must add some event listeners.
*/
connection.onmessage = (event) => {
  const data = JSON.parse(event.data);
  displayMessages({
    display_name: data.Sender.Attributes.DisplayName,
    message: data.Content,
    timestamp: data.SendTime
  });
}

function displayMessages(message) {
  // Modify this function to display messages in your chat UI however you like.
  console.log(message);
}

/*
4. Delete a chat message by sending the DELETE_MESSAGE action to the WebSocket 
connection. The connected user must have the "DELETE_MESSAGE" permission to 
perform this action.
*/

function deleteMessage(messageId) {
  const deletePayload = {
    "Action": "DELETE_MESSAGE",
    "Reason": "Deleted by moderator",
    "Id": "${messageId}"
  }
  connection.send(deletePayload);
}
```

おめでとうございます、これで準備万端です！これで、メッセージを送受信できるシンプルなチャットアプリケーションができました。