[英]Getting Connection Refused with WCF Service
我使用WCF进行了服务,但无法连接到该服务,但不断出现以下错误:
无法连接到net.tcp:// localhost:5555 / ControlChannel。 连接尝试持续时间为00:00:02.0139182。 TCP错误代码10061:无法建立连接,因为目标计算机主动拒绝它127.0.0.1:5555。
这是代码:
合同:
[ServiceContract(CallbackContract = typeof(IControlChannelCallback))]
public interface IControlChannel
{
[OperationContract]
void Join();
}
CallBackContract:
public interface IControlChannelCallback
{
[OperationContract(IsOneWay = true)]
void ShowMessage(string message);
}
服务:
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
public sealed class ControlChannel : IControlChannel
{
public static readonly IList<IControlChannelCallback> Callbacks = new List<IControlChannelCallback>();
public void Join()
{
var client = OperationContext.Current.GetCallbackChannel<IControlChannelCallback>();
if (!Callbacks.Contains(client))
Callbacks.Add(client);
client.ShowMessage("This message came from the server");
}
}
服务器:
public MainForm()
{
InitializeComponent();
using (var host = new ServiceHost(typeof(ControlChannel)))
{
host.Open();
}
}
客户:
public MainForm()
{
InitializeComponent();
var callback = new ControlChannelCallbackClient();
using (var factory = new DuplexChannelFactory<IControlChannel>(callback, "Client"))
{
var proxy = factory.CreateChannel();
proxy.Join();
}
}
App.config客户端:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<client>
<endpoint name="Client"
contract="Service.Contracts.Interfaces.IControlChannel"
binding="netTcpBinding"
address="net.tcp://localhost:5555/ControlChannel" />
</client>
</system.serviceModel>
</configuration>
App.config服务器
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<services>
<service name="Service.Contracts.Objects.ControlChannel">
<endpoint contract="Service.Contracts.Interfaces.IControlChannel"
binding="netTcpBinding"
address="net.tcp://localhost:5555/ControlChannel" >
</endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
我究竟做错了什么? 是代码问题还是我应该开始在其他地方寻找问题?
只是预感,但我怀疑没有人在听,因为即使托管您的服务的应用程序可能仍在运行,但服务主机却没有。 在您的构造函数中:
public MainForm()
{
InitializeComponent();
using (var host = new ServiceHost(typeof(ControlChannel)))
{
host.Open();
}
}
您将ServiceHost
放在using
块中ServiceHost
块退出后(就在构造函数完成之前), ServiceHost
将被关闭并处置。
将您的代码更改为此:
public MainForm()
{
InitializeComponent();
var host = new ServiceHost(typeof(ControlChannel))
host.Open();
}
您可以挂钩到应用程序关闭事件,以在程序运行结束时关闭ServiceHost
。
我还建议将host.Open()
包装在try-catch块中,以防尝试打开它时出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.