■WCFとは何か?
WCF(Windows Communication Foundation)とは、マイクロソフトが.Net Framework 3.0で提供している通信基盤技術です。
ASP.NET Webサービス、Enterprise Services、WSE、System.Messaging、.Net Remotingなどを
統一したものになります。
属性ベースの定義が出来たり、セキュリティ、トランザクションが標準機能になっているのが特徴です。
■WCFの仕組み
WCFを理解するうえで必要な定義を”ABC”といいます。
ABCとは、「Where」・「How」・「What」を示しています。
A(Where):アドレス
アドレスは、どのアドレスに対してメッセージを送るか、どのアドレスでメッセージを受け取るのかを定義します。
B(How):バインディング
バインディングは、どのようにメッセージを送るのか、受け取るのかを定義します。
C(What):コントラクト
コントラクトは、何を通信するのかを定義します。
■とりあえず実装してみる
WCFについて基本的なことを色々調べてはみましたが、いまいち理解が進まなかったので、
実装してみました。
とりあえず、テストが簡単なプロセス間通信を利用するアプリを作ってみました。
アプリ概要は以下の3つです。
WcfServiceContract:コントラクト
WcfClient:メッセージを送信アプリ(Windowsフォーム)
WcfServer:メッセージを受信するアプリ(コンソールアプリ)
using System.ServiceModel;
namespace WcfServiceContract
{
[ServiceContract]
public interface IServiceContract
{
[OperationContract]
void SendMessage(string message);
}
}
using System.ServiceModel;
using WcfServiceContract;
namespace WcfClient
{
public partial class Form1 : Form
{
IServiceContract client = null;
public Form1()
{
InitializeComponent();
// チャネル作成
client = new ChannelFactory(
new NetNamedPipeBinding(),
"net.pipe://localhost/WcfConnection/").CreateChannel();
}
private void button1_Click(object sender, EventArgs e)
{
client.SendMessage(textBox1.Text);
}
}
}
using System.ServiceModel;
using WcfServiceContract;
namespace WcfServer
{
class Program
{
static ServiceHost host = null;
static void Main(string[] args)
{
WcfReceveService server = new WcfReceveService();
server.ReceveEvent += new Action(server_ReceveEvent);
host = new ServiceHost(server);
host.AddServiceEndpoint(
typeof(IServiceContract),
new NetNamedPipeBinding(),
"net.pipe://localhost/WcfConnection/");
host.Open();
Console.WriteLine("Server Opne");
Console.ReadLine();
}
static void server_ReceveEvent(string obj)
{
Console.WriteLine(obj);
}
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
internal class WcfReceveService : IServiceContract
{
public event ActionReceveEvent = null;
public void SendMessage(string message)
{
if (ReceveEvent != null)
{
ReceveEvent(message);
}
}
}
}
今回名前付きパイプで、手軽にプロセス間通信できました。
通信といっても、クライアントは、インターフェイスの関数を呼び出すだけで済むし、
サーバーもインターフェイスを継承したクラスでイベント通知してしまえば、通常のアプリとして実装ができました。
思っていた以上に簡単に実装できて驚きました。
ただ、このクライアントアプリは、少し時間をおき、いきなりサーバーにアクセスするとエラーが発生します。原因は分かりません。
次回は、この原因を調べてみたいと思います。