步骤 4:发送和接收第一条消息 - Amazon IVS

步骤 4:发送和接收第一条消息

使用聊天令牌连接到聊天室并发送第一条消息。以下是 JavaScript 示例代码。此外,还提供了 IVS 客户端 SDK:请参阅 Chat SDK: Android GuideChat SDK: iOS Guide 和 Chat SDK: JavaScript Guide

区域服务:以下示例代码是指您的“受支持的选择区域”。Amazon IVS Chat 提供了可用于发出请求的区域端点。对于 Amazon IVS Chat Messaging API,区域端点的一般语法为:

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

例如,美国西部(俄勒冈州)区域的端点为 wss://edge.ivschat.us-west-2.amazonaws.com。有关受支持区域的列表,请参阅《AWS 一般参考》中 Amazon IVS 页面上的 Amazon IVS 聊天功能信息。

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

恭喜您,一切准备就绪!现在,您已拥有一个简单的聊天应用程序,可以发送或接收消息。