2012-02-05 53 views
1

我已经实现了一个简单的聊天控制台应用程序,它运行良好。当我试图在GUI应用程序上应用相同的概念时。服务端托管时,有任何错误,但如果我使用CMD命令netstat -ao显示所有端口,它不存在。因此,当我运行客户端应用程序,有一个例外(无法连接,因为目标机器积极拒绝)。我如何解决这些问题?WCF服务不在机器上

服务器

ServiceHost host; 
using (host = new ServiceHost(typeof(Service), new Uri("net.tcp://localhost:4111"))) 
{ 
    host.AddServiceEndpoint(typeof(IService), new NetTcpBinding(), "IService"); 

    try 
    { 
     host.Open(); 

    } 
    catch 
    { 
    } 
} 

客户

public bool Connect() 
{ 
    DuplexChannelFactory<IService> pipeFactory = new DuplexChannelFactory<IService>(new InstanceContext(this), 
                        new NetTcpBinding(), 
                        new EndpointAddress(AppConfiguration.GetValue(net.tcp://localhost:4111/IService")); 

    try 
    { 
     pipeProxy = pipeFactory.CreateChannel(); 
     if (pipeProxy.Register()) 
     { 
      return true; 
     } 
    } 
    catch 
    { 
    } 
    return false; 
} 
+1

您是否试图从与服务器相同的计算机运行客户端?如果没有,'net.tcp:// localhost:4111'会出现问题。 – 2012-02-05 01:08:28

回答

0

我已经解决了。 在GUI中删除(使用)定义的新ServiceHost。为什么我不知道,但它的作品!

ServiceHost host; 
host = new ServiceHost(typeof(Service), new Uri("net.tcp://localhost:4111")); 
+0

不要这样做! “使用”是控制资源处置的句法糖。这个'工作'的原因是因为你已经删除了处理完ServiceHost的代码。从你的问题中不清楚问题是什么,但是你应该确定恢复'使用'块。它的存在是有原因的。 – 2012-02-08 14:03:25

0

假设你是显示所有的代码。你需要在host.Open()之后添加一行,你可以添加Console.ReadLine()。

这会让程序停止存在。现在发生的事情是主机打开,然后程序存在,主机被关闭/垃圾收集。