WCF点对点聊天

时间:2009-10-05 13:21:32

标签: wcf p2p pnrp

我为WCF P2P聊天程序编写了一些代码。

<services>
  <service name="PeerChat.Form1">
    <host>
      <baseAddresses>
        <add baseAddress="net.p2p://PeerChat/" />
      </baseAddresses>
    </host>
    <endpoint name="PeerChatEndPoint" address="" binding="netPeerTcpBinding" bindingConfiguration="BindingUnsecure"
       contract="PeerChat.IChatService" />
  </service>
</services>
<bindings>
  <netPeerTcpBinding>
    <binding name="BindingUnsecure">
      <resolver mode="Pnrp" />
      <security mode="None" />
    </binding>
  </netPeerTcpBinding>
</bindings>
<client>
  <endpoint
      name="PeerChatClientEndPoint"
      address="net.p2p://PeerChat/"
      binding="netPeerTcpBinding"
      bindingConfiguration="BindingUnsecure"
      contract="PeerChat.IChatService"
  />
</client>

然后我按照以下方式托管服务:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public partial class Form1 : Form, IChatService
{

    IChatService channel;
    ServiceHost host = null;
    ChannelFactory<IChatService> channelFactory = null;

    private void StartService()
    {
        //Instantiate new ServiceHost
        host = new ServiceHost(this);
        //Open ServiceHost
        host.Open();
        //Create a ChannelFactory and load the configuration setting
        channelFactory = new ChannelFactory<IChatService>("PeerChatClientEndPoint");
        channel = channelFactory.CreateChannel();
        //Lets others know that someone new has joined
        channel.SendMessage("Hello."+ Environment.NewLine);

        foreach (var cloud in Cloud.GetAvailableClouds())
        {
            textBox2.Text += cloud.Name + Environment.NewLine;
        }
    }
    private void StopService()
    {
        if (host != null)
        {
            channel.SendMessage("Bye." + Environment.NewLine);
            if (host.State != CommunicationState.Closed)
            {
                channelFactory.Close();
                host.Close();
            }
        }
    }

问题是我可以向同一个程序实例发送消息,但不能向另一个实例发送消息。即实例仅接收其自己的消息而不是来自其他实例的消息。不确定是否正确配置PNRP?我在Windows 7上测试过。

1 个答案:

答案 0 :(得分:1)

你不会碰巧让程序的两个实例都听同一个终点吗?我不确定,但我怀疑可能发生的事情是您的客户端应用程序首先在端点上注册自己,然后在第二个端点可以获取之前拦截到达该端点的所有消息。我建议尝试做的是配置第二个实例以使用不同的Uri启动端点。所以说一个连接net.p2p:// PeerChatA /和另一个net.p2p:// PeerChatB /。