첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

728x90
반응형

▶ OrderRequest.cs (서버)

using System;
using System.ServiceModel;

namespace TestProject
{
    /// <summary>
    /// 주문 요청
    /// </summary>
    [MessageContract(WrapperName = "Order")]
    public class OrderRequest
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region Field

        /// <summary>
        /// 패스워드
        /// </summary>
        [MessageHeader]
        public string Password = null;

        /// <summary>
        /// 사용자 ID
        /// </summary>
        [MessageBodyMember(Name = "userID", Order = 1)]
        public string UserID = null;

        /// <summary>
        /// ISBN
        /// </summary>
        [MessageBodyMember(Name = "isbn", Order = 2)]
        public string ISBN = null;

        /// <summary>
        /// 수량
        /// </summary>
        [MessageBodyMember(Name = "amount", Order = 3)]
        public int Amount = 0;

        #endregion
    }
}

 

▶ OrderResponse.cs (서버)

using System;
using System.ServiceModel;

namespace TestProject
{
    /// <summary>
    /// 주문 회신
    /// </summary>
    [MessageContract]
    public class OrderResponse
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region Field

        /// <summary>
        /// 주문 결과
        /// </summary>
        [MessageBodyMember]
        public int OrderResult = 0;

        #endregion
    }
}

 

▶ IBookStore.cs (서버)

using System;
using System.ServiceModel;

namespace TestProject
{
    /// <summary>
    /// 상점 인터페이스
    /// </summary>
    [ServiceContract(Namespace = "http://company.com/bookstore")]
    public interface IBookStore
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        #region 주문하기 - Order(orderRequest)

        /// <summary>
        /// 주문하기
        /// </summary>
        /// <param name="orderRequest">주문 요청</param>
        /// <returns>주문 회신</returns>
        [OperationContract]
        OrderResponse Order(OrderRequest orderRequest);

        #endregion
    }
}

 

▶ BookStoreService.cs (서버)

using System;
using System.ServiceModel;

namespace TestProject
{
    /// <summary>
    /// 상점 서비스
    /// </summary>
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class BookStoreService : IBookStore
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 주문 ID
        /// </summary>
        private static int _orderID = 0;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 주문하기 - Order(orderRequest)

        /// <summary>
        /// 주문하기
        /// </summary>
        /// <param name="orderRequest">주문 요청</param>
        /// <returns>주문 ID</returns>
        public OrderResponse Order(OrderRequest orderRequest)
        {
            string userID = orderRequest.UserID;
            string isbn   = orderRequest.ISBN;
            int    amount = orderRequest.Amount;

            if(string.IsNullOrEmpty(orderRequest.Password) || orderRequest.Password != "password")
            {
                throw new InvalidOperationException("무효한 클라이언트 호출 입니다.");
            }

            int price = GetUnitPrice(isbn) * amount;

            _orderID += 1;

            Console.WriteLine
            (
                "도서 주문 : 주문 ID={0}\n            사용자 ID={1}, ISBN={2}, 수량={3}, 가격={4}",
                _orderID,
                userID,
                isbn,
                amount,
                price
            );

            OrderResponse orderResponse = new OrderResponse();

            orderResponse.OrderResult = _orderID;

            return orderResponse;
        }

        #endregion

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region 단가 구하기 - GetUnitPrice(isbn)

        /// <summary>
        /// 단가 구하기
        /// </summary>
        /// <param name="isbn">ISBN</param>
        /// <returns>단가</returns>
        private int GetUnitPrice(string isbn)
        {
            return 35000;
        }

        #endregion
    }
}

 

▶ Program.cs (서버)

using System;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace TestProject
{
    /// <summary>
    /// 프로그램
    /// </summary>
    public class Program
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Private

        #region 프로그램 시작하기 - Main()

        /// <summary>
        /// 프로그램 시작하기
        /// </summary>
        private static void Main()
        {
            Console.WriteLine("메시지 계약 테스트 서버를 시작합니다...");

            ServiceHost serviceHost = new ServiceHost
            (
                typeof(BookStoreService),
                new Uri("http://localhost/wcf/bookstoreservice")
            );

            BasicHttpBinding basicHttpBinding = new BasicHttpBinding();

            serviceHost.AddServiceEndpoint(typeof(IBookStore), basicHttpBinding, string.Empty);

            ServiceMetadataBehavior serviceMetadataBehavior = new ServiceMetadataBehavior();

            serviceMetadataBehavior.HttpGetEnabled = true;

            serviceHost.Description.Behaviors.Add(serviceMetadataBehavior);

            serviceHost.Open();

            Console.WriteLine("서비스 중단을 위해 아무 키나 누르세요...");

            Console.ReadKey(true);

            serviceHost.Close();
        }

        #endregion
    }
}

 

▶ app.config (클라이언트)

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IBookStore" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint name="BasicHttpBinding_IBookStore"
                address="http://localhost/wcf/bookstoreservice"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IBookStore"
                contract="BookStoreService.IBookStore" />
        </client>
    </system.serviceModel>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
    </startup>
</configuration>

 

▶ Program.cs (클라이언트)

using System;

using TestProject.BookStore;

namespace TestProject
{
    public class Program
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public

        #region 프로그램 시작하기 - Main()

        /// <summary>
        /// 프로그램 시작하기
        /// </summary>
        private static void Main()
        {
            Console.WriteLine("메시지 계약 테스트 클라이언트를 시작합니다...");

            int    orderID;
            string password = "password";

            using(BookStoreClient bookStoreClient = new BookStoreClient())
            {
                orderID = bookStoreClient.Order(password, "사용자1", "999-9-999-99999-9", 2);

                Console.WriteLine("주문하였습니다 : 주문 ID = {0}", orderID);
            }
        }

        #endregion
    }
}

※ BookStoreClient 클래스는 서비스 참조 추가를 통해 생성한다.

728x90
반응형
Posted by 사용자 icodebroker
TAG , ,

댓글을 달아 주세요