

的版本 4 (V4) 适用于 .NET 的 Amazon SDK 已经发布！

有关重大更改和迁移应用程序的信息，请参阅[迁移主题](https://docs.amazonaws.cn/sdk-for-net/v4/developer-guide/net-dg-v4.html)。

 [https://docs.amazonaws.cn/sdk-for-net/v4/developer-guide/net-dg-v4.html](https://docs.amazonaws.cn/sdk-for-net/v4/developer-guide/net-dg-v4.html)

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 发送 Amazon SMS 消息
发送消息

[此示例向您展示如何使用向 Amazon SQS 队列发送消息，您可以通过[编程方式](CreateQueue.md)或使用 Amazon SQS 控制台创建该队列。 适用于 .NET 的 Amazon SDK](https://console.amazonaws.cn/sqs)应用程序向队列发送一条消息，然后发送一批消息。然后，应用程序等待用户输入，这些输入可以是要发送到队列的额外消息或退出应用程序的请求。

此示例和[下一个有关接收消息的示例](ReceiveMessage.md)可以一起使用，以查看 Amazon SQS 中的消息流。

以下各节提供了此示例的片段。此后显示了[该示例的完整代码](#SendMessage-complete-code)，并且可以按原样构建和运行。

**Topics**
+ [

## 发送消息
](#SendMessage-send-message)
+ [

## 发送一批消息
](#SendMessage-send-batch)
+ [

## 从队列中删除所有消息
](#SendMessage-purge-messages)
+ [

## 完整代码
](#SendMessage-complete-code)
+ [

## 其他注意事项
](#SendMessage-additional)

## 发送消息


以下代码片段将消息发送到由给定队列 URL 标识的队列。

[本主题末尾](#SendMessage-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to put a message on a queue
    // Could be expanded to include message attributes, etc., in a SendMessageRequest
    private static async Task SendMessage(
      IAmazonSQS sqsClient, string qUrl, string messageBody)
    {
      SendMessageResponse responseSendMsg =
        await sqsClient.SendMessageAsync(qUrl, messageBody);
      Console.WriteLine($"Message added to queue\n  {qUrl}");
      Console.WriteLine($"HttpStatusCode: {responseSendMsg.HttpStatusCode}");
    }
```

## 发送一批消息


以下代码片段向由给定队列 URL 标识的队列发送一批消息。

[本主题末尾](#SendMessage-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to put a batch of messages on a queue
    // Could be expanded to include message attributes, etc.,
    // in the SendMessageBatchRequestEntry objects
    private static async Task SendMessageBatch(
      IAmazonSQS sqsClient, string qUrl, List<SendMessageBatchRequestEntry> messages)
    {
      Console.WriteLine($"\nSending a batch of messages to queue\n  {qUrl}");
      SendMessageBatchResponse responseSendBatch =
        await sqsClient.SendMessageBatchAsync(qUrl, messages);
      // Could test responseSendBatch.Failed here
      foreach(SendMessageBatchResultEntry entry in responseSendBatch.Successful)
        Console.WriteLine($"Message {entry.Id} successfully queued.");
    }
```

## 从队列中删除所有消息


以下代码片段删除了来自由给定队列 URL 标识的队列的所有消息。这也称为*清除队列*。

[本主题末尾](#SendMessage-complete-code)的示例显示了此片段的使用情况。

```
    //
    // Method to delete all messages from the queue
    private static async Task DeleteAllMessages(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"\nPurging messages from queue\n  {qUrl}...");
      PurgeQueueResponse responsePurge = await sqsClient.PurgeQueueAsync(qUrl);
      Console.WriteLine($"HttpStatusCode: {responsePurge.HttpStatusCode}");
    }
```

## 完整代码


本部分显示了本示例的相关参考和完整代码。

### SDK 参考


NuGet 包裹：
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

编程元素：
+ 命名空间 [Amazon.SQS](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQS.html)

  [Amazon 上](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSQSClient.html)课 SQSClient
+ 命名空间 [Amazon.SQS.Model](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/NSQSModel.html)

  班级 [PurgeQueueResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TPurgeQueueResponse.html)

  班级 [SendMessageBatchResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSendMessageBatchResponse.html)

  班级 [SendMessageResponse](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSendMessageResponse.html)

  班级 [SendMessageBatchRequestEntry](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSendMessageBatchRequestEntry.html)

  班级 [SendMessageBatchResultEntry](https://docs.amazonaws.cn/sdkfornet/v4/apidocs/items/SQS/TSendMessageBatchResultEntry.html)

### 代码


```
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSSendMessages
{
  // = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
  // Class to send messages to a queue
  class Program
  {
    // Some example messages to send to the queue
    private const string JsonMessage = "{\"product\":[{\"name\":\"Product A\",\"price\": \"32\"},{\"name\": \"Product B\",\"price\": \"27\"}]}";
    private const string XmlMessage = "<products><product name=\"Product A\" price=\"32\" /><product name=\"Product B\" price=\"27\" /></products>";
    private const string CustomMessage = "||product|Product A|32||product|Product B|27||";
    private const string TextMessage = "Just a plain text message.";

    static async Task Main(string[] args)
    {
      // Do some checks on the command-line
      if(args.Length == 0)
      {
        Console.WriteLine("\nUsage: SQSSendMessages queue_url");
        Console.WriteLine("   queue_url - The URL of an existing SQS queue.");
        return;
      }
      if(!args[0].StartsWith("https://sqs."))
      {
        Console.WriteLine("\nThe command-line argument isn't a queue URL:");
        Console.WriteLine($"{args[0]}");
        return;
      }

      // Create the Amazon SQS client
      var sqsClient = new AmazonSQSClient();

      // (could verify that the queue exists)
      // Send some example messages to the given queue
      // A single message
      await SendMessage(sqsClient, args[0], JsonMessage);

      // A batch of messages
      var batchMessages = new List<SendMessageBatchRequestEntry>{
        new SendMessageBatchRequestEntry("xmlMsg", XmlMessage),
        new SendMessageBatchRequestEntry("customeMsg", CustomMessage),
        new SendMessageBatchRequestEntry("textMsg", TextMessage)};
      await SendMessageBatch(sqsClient, args[0], batchMessages);

      // Let the user send their own messages or quit
      await InteractWithUser(sqsClient, args[0]);

      // Delete all messages that are still in the queue
      await DeleteAllMessages(sqsClient, args[0]);
    }


    //
    // Method to put a message on a queue
    // Could be expanded to include message attributes, etc., in a SendMessageRequest
    private static async Task SendMessage(
      IAmazonSQS sqsClient, string qUrl, string messageBody)
    {
      SendMessageResponse responseSendMsg =
        await sqsClient.SendMessageAsync(qUrl, messageBody);
      Console.WriteLine($"Message added to queue\n  {qUrl}");
      Console.WriteLine($"HttpStatusCode: {responseSendMsg.HttpStatusCode}");
    }


    //
    // Method to put a batch of messages on a queue
    // Could be expanded to include message attributes, etc.,
    // in the SendMessageBatchRequestEntry objects
    private static async Task SendMessageBatch(
      IAmazonSQS sqsClient, string qUrl, List<SendMessageBatchRequestEntry> messages)
    {
      Console.WriteLine($"\nSending a batch of messages to queue\n  {qUrl}");
      SendMessageBatchResponse responseSendBatch =
        await sqsClient.SendMessageBatchAsync(qUrl, messages);
      // Could test responseSendBatch.Failed here
      foreach(SendMessageBatchResultEntry entry in responseSendBatch.Successful)
        Console.WriteLine($"Message {entry.Id} successfully queued.");
    }


    //
    // Method to get input from the user
    // They can provide messages to put in the queue or exit the application
    private static async Task InteractWithUser(IAmazonSQS sqsClient, string qUrl)
    {
      string response;
      while (true)
      {
        // Get the user's input
        Console.WriteLine("\nType a message for the queue or \"exit\" to quit:");
        response = Console.ReadLine();
        if(response.ToLower() == "exit") break;

        // Put the user's message in the queue
        await SendMessage(sqsClient, qUrl, response);
      }
    }


    //
    // Method to delete all messages from the queue
    private static async Task DeleteAllMessages(IAmazonSQS sqsClient, string qUrl)
    {
      Console.WriteLine($"\nPurging messages from queue\n  {qUrl}...");
      PurgeQueueResponse responsePurge = await sqsClient.PurgeQueueAsync(qUrl);
      Console.WriteLine($"HttpStatusCode: {responsePurge.HttpStatusCode}");
    }
  }
}
```

## 其他注意事项

+ 有关消息的各种限制（包括允许的字符）的信息，请参阅 [Amazon Simple Queue Service 开发人员指南](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/)中[与消息相关的配额](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages)部分。
+ 消息会一直保留在队列中，直到被删除或队列被清除。当应用程序收到一条消息时，即使它仍然存在于队列中，它也不会出现在队列中。有关可见性超时的更多信息，请参阅 [Amazon SQS 可见性超时](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html)。
+ 除了消息正文外，您还可以为消息添加属性。有关更多信息，请参阅[消息元数据](https://docs.amazonaws.cn/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html)。