Silverlight通过TCP协议访问双工模式的WCF(Host在控制台)

Siverlight与WCF之间的通信按照理论有以下几种方式

协议  宿主 

http  console

http  IIS

tcp    console

tcp    IIS

当然还有windows服务,winform等等,这里仅举出了常见的两种。

这次测试的是silverlight使用TCP访问寄宿在控制台上的wcf服务

代码结构:

image

双工访问的关键点在于

1,比普通的WCF服务多了一个回调契约

namespace WCFLibrary
{
    [ServiceContract(CallbackContract = typeof(IUpdateClient))]   
    public interface IUpdateUser
    {
        [OperationContract]
        WCFModel.User Update(WCFModel.User User);
    }

    [ServiceContract]
    public interface IUpdateClient
    {
        [OperationContract(IsOneWay = true)]
        void Say(string fromServerString);
    }
}

2,app.config配置

<service behaviorConfiguration="WCFLibrary.UpdateUserBehavior" name="WCFLibrary.UpdateUser">
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:4503/UpdateUser"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="netTcpBinding" contract="WCFLibrary.IUpdateUser" bindingConfiguration="netTcpBindConfig"></endpoint>
        <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" ></endpoint>
      </service>

3,一定要在本机的IIS根目录放置一个策略文件

image

4,Host关键代码

class Program
    {
        static void Main(string[] args)
        {
            MyHost.Open();
            System.Console.WriteLine("服t务?已?经-启?动ˉ...   敲?任?意a键ü停£止1服t务?");
            System.Console.ReadLine();
            MyHost.Close();
        }
    }

    public class MyHost
    {
        static ServiceHost host = null;
        public static void Open()
        {
            host = new ServiceHost(typeof(WCFLibrary.UpdateUser));
            host.Open();

            host = new ServiceHost(typeof(WCFLibrary.AddService));
            host.Open();
        }
        public static void Close()
        {
            if (host != null && host.State == CommunicationState.Opened)
            {
                host.Close();
            }
            host = null;
        }
    }
 
源代码:https://files.cnblogs.com/wengyuli/WCFTCPDuplex.rar
posted @ 2010-09-08 19:53  翁玉礼  阅读(2736)  评论(2编辑  收藏  举报