

# 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 Messaging API의 경우 리전 엔드포인트의 일반 구문은 다음과 같습니다.
+ wss://edge.ivschat.<region-code>.amazonaws.com

예를 들어 wss://edge.ivschat.us-west-2.amazonaws.com은 미국 서부(오레곤) 리전의 엔드포인트입니다. 지원되는 리전 목록은 [AWS 일반 참조](https://docs.aws.amazon.com/general/latest/gr/ivs.html)의 *Amazon IVS 페이지*에서 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);
}
```

축하합니다. 모두 설정되었습니다. 이제 메시지를 전송하거나 수신할 수 있는 간단한 채팅 애플리케이션이 생겼습니다.