Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

メッセージ交換パターンの検証(その1)

エントリーを2度に分けてWCFの3種類のメッセージ交換パターン(要求/応答、一方向、双方向)を検証します。
今回はWCFサービスを実装します。

WCFサービスのソースコード

IService1.cs
using System.ServiceModel;
using Client;

namespace MEPService {
    [ServiceContract(
        SessionMode = SessionMode.Required,
        CallbackContract = typeof(ITestDuplexCallback))]
    public interface IService1 {
        // 要求/応答パターン
        [OperationContract(IsOneWay = false)]
        void TestOneWayFalse();

        // 一方向パターン
        // IsOneWayプロパティにtrueをセットすると、呼出し後ただしに制御が戻ります。
        [OperationContract(IsOneWay = true)]
        void TestOneWayTrue;

        // 双方向パターン
        [OperationContract(IsOneWay = true)]
        void TestDuplex;
    }
}
ITestDuplexCallback.cs
using System.ServiceModel;

namespace Client {
    /// <summary>
    /// クライアントに通知するためのコールバックインターフェース
    /// </summary>
    interface ITestDuplexCallback {
        [OperationContract(IsOneWay = true)]
        void SendMessage(string message);
    }
}
Service1.cs
using System.Diagnostics;
using System.ServiceModel;
using System.Threading;
using Client;

namespace MEPService {
    public class Service1 : IService1 {
        private ITestDuplexCallback callback = null;

        public Service1() {
            callback = OperationContext.Current.GetCallbackChannel<ITestDuplexCallback>();
        }

        #region IService1 メンバー

        // 要求/応答パターン
        public void TestOneWayFalse() {
            Thread.Sleep(5000);
        }

        // 一方向パターン
        public void TestOneWayTrue() {
            Thread.Sleep(5000);
        }

        // 双方向パターン
        public void TestDuplex() {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            Thread.Sleep(5000);
            stopwatch.Stop();

            // コールバックインターフェースを通じてクライアント側に経過時間を通知
            callback.SendMessage(stopwatch.ToString());
        }

        #endregion
    }
}