

 AWS SDK for .NET V3가 유지 관리 모드로 전환되었습니다.

[AWS SDK for .NET V4](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html)로 마이그레이션하는 것이 좋습니다. 마이그레이션 방법에 대한 자세한 내용과 정보는 [유지 관리 모드 공지](https://aws.amazon.com/blogs/developer/aws-sdk-for-net-v3-maintenance-mode-announcement/)를 참조하세요.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Amazon SQS 메시지 전송
<a name="SendMessage"></a>

이 예제에서는 AWS SDK for .NET 를 사용하여 [프로그래밍 방식으로](CreateQueue.md) 또는 Amazon SQS [콘솔을 사용하여 생성할 수 있는 Amazon SQS ](https://console.aws.amazon.com/sqs)대기열로 메시지를 전송하는 방법을 보여줍니다. 애플리케이션은 대기열에 메시지 하나를 전송한 다음 메시지 배치를 전송합니다. 그러면 애플리케이션은 사용자 입력을 기다립니다. 사용자 입력은 대기열에 보낼 추가 메시지나 애플리케이션 종료 요청일 수 있습니다.

이 예제와 [메시지 수신에 대한 다음 예제](ReceiveMessage.md)를 함께 사용하여 Amazon SQS의 메시지 흐름을 확인할 수 있습니다.

다음 섹션에서는 이 예제의 코드 조각을 제공합니다. [예제의 전체 코드](#SendMessage-complete-code)는 그 뒤에 표시되며, 그대로 빌드하고 실행할 수 있습니다.

**Topics**
+ [

## 메시지 전송
](#SendMessage-send-message)
+ [

## 메시지 배치 전송
](#SendMessage-send-batch)
+ [

## 대기열에서 모든 메시지 삭제
](#SendMessage-purge-messages)
+ [

## 전체 코드
](#SendMessage-complete-code)
+ [

## 추가 고려 사항
](#SendMessage-additional)

## 메시지 전송
<a name="SendMessage-send-message"></a>

다음 코드 조각은 지정된 대기열 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}");
    }
```

## 메시지 배치 전송
<a name="SendMessage-send-batch"></a>

다음 코드 조각은 지정된 대기열 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.");
    }
```

## 대기열에서 모든 메시지 삭제
<a name="SendMessage-purge-messages"></a>

다음 코드 조각은 지정된 대기열 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}");
    }
```

## 전체 코드
<a name="SendMessage-complete-code"></a>

이 섹션에는 이 예제에 대한 관련 참조와 전체 코드가 나와 있습니다.

### SDK 레퍼런스
<a name="w2aac19c15c25c23c25b5b1"></a>

NuGet 패키지:
+ [AWSSDK.SQS](https://www.nuget.org/packages/AWSSDK.SQS)

프로그래밍 요소:
+ 네임스페이스 [Amazon.SQS](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQS.html)

  클래스 [AmazonSQSClient](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSQSClient.html)
+ 네임스페이스 [Amazon.SQS.Model](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/NSQSModel.html)

  클래스 [PurgeQueueResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TPurgeQueueResponse.html)

  클래스 [SendMessageBatchResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageBatchResponse.html)

  클래스 [SendMessageResponse](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageResponse.html)

  클래스 [SendMessageBatchRequestEntry](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageBatchRequestEntry.html)

  클래스 [SendMessageBatchResultEntry](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/SQS/TSendMessageBatchResultEntry.html)

### 코드
<a name="w2aac19c15c25c23c25b7b1"></a>

```
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}");
    }
  }
}
```

## 추가 고려 사항
<a name="SendMessage-additional"></a>
+ 허용되는 문자를 비롯한 다양한 메시지 제한 사항에 대한 자세한 내용은 [Amazon Simple Queue Service 개발자 안내서](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/)의 [메시지 관련 할당량](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages)을 참조하세요.
+ 메시지는 삭제되거나 대기열이 제거될 때까지 대기열에 남아 있습니다. 애플리케이션이 메시지를 수신한 경우 해당 메시지가 대기열에 남아 있더라도 대기열에 표시되지 않습니다. 제한 시간 초과에 대한 자세한 내용은 [Amazon SQS 제한 시간 초과](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/AboutVT.html)를 참조하세요.
+ 메시지 본문 외에도 메시지에 속성을 추가할 수 있습니다. 자세한 내용은 [메시지 메타데이터](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html)를 참조하세요.