愚者之居

专注于软件的研究与开发

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

用console做WCF宿主的例子

嗯,现在有个问题的确摆在了我们眼前,不管怎么样,不能靠类库吃一辈子吧?总要学会自己构建一个服务器的吧。

那好,我们来制作一个服务器吧。

创建一个windows控制台项目,命名为Host

对Host添加.NET System.ServiceModel名空间引用

对Host添加刚才生成的WCF项目,注意,不是引用服务,就是引用本地项目类库,我们的目标是不再使用wcf默认的服务器了。

然后对Host项目添加项目配置文件App.config

将WCF类库中自动生成的App.config内容原封不动的全部拷贝到Host项目的App.config中

编写Host中的主文件如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.ComponentModel;
using System.Timers;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using WcfServiceLibrary1;
namespace ConsoleWcfService
{
    class Program
    {
        static public int aa = 0;
        static private System.Timers.Timer timer = new Timer();
        //static private SerialPort serialPort = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
        static private void MyTimer()
        {
            Console.WriteLine(DateTime.Now.ToString());
            aa = aa + 1;
        }
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8001/");

            ServiceHost Host = new ServiceHost(typeof(Service1), baseAddress);

            Host.AddServiceEndpoint(typeof(IService1), new BasicHttpBinding(), "manualWCF");

            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            Host.Description.Behaviors.Add(smb);
            Host.Open();

            timer.Interval = 100;
            // serialPort.DataReceived += new SerialDataReceivedEventHandler(MyDataReceived);
            timer.Elapsed += delegate { MyTimer(); };

            timer.Start();
            Console.WriteLine("The manual WCF is running at " + baseAddress.ToString() + "manualWCF");
            Console.WriteLine("Press <ENTER> to terminate");
            Console.ReadLine();

            Host.Close();
        }
    }
}

posted on 2010-05-02 11:09  Jacky.Tao  阅读(576)  评论(0)    收藏  举报