Etapa 4: enviar e receber sua primeira mensagem - Amazon IVS

Etapa 4: enviar e receber sua primeira mensagem

Use o token do chat para se conectar a uma sala de chat e enviar sua primeira mensagem. Veja um exemplo de código JavaScript abaixo. Os SDKs do cliente do IVS também estão disponíveis: consulte Chat SDK: Android Guide, Chat SDK: iOS Guide e Chat SDK: JavaScript Guide.

Serviço regional: o exemplo de código abaixo se refere à “região de sua preferência compatível”. O Amazon IVS Chat oferece endpoints regionais que podem ser usados para fazer as solicitações. Para a API do Amazon IVS Chat Messaging, a sintaxe geral de um endpoint regional é:

  • wss://edge.ivschat.<region-code>.amazonaws.com

Por exemplo, wss://edge.ivschat.us-west-2.amazonaws.com é o endpoint da região Oeste dos EUA (Oregon). Para obter uma lista das regiões compatíveis, consulte as informações sobre o Amazon IVS Chat na página do Amazon IVS na AWS General Reference (Referência geral da AWS).

/* 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); }

Parabéns, já está tudo pronto! Agora você tem uma aplicação de chat simples que pode enviar ou receber mensagens.