运行客户端代码时,第一次尝试在IWcfServer接口上调用方法时,连接会立即中断,并显示以下消息:
+11:00
这一切在调用客户端代码的一秒钟内发生。
服务器代码:
System.ServiceModel.CommunicationException: 'The socket connection was aborted.
This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue.
Local socket timeout was '00:00:59.6090000'.'
客户代码:
Dim binding As New NetTcpBinding()
binding.Security.Mode = SecurityMode.Transport
binding.MaxReceivedMessageSize = 10000000
binding.OpenTimeout = TimeSpan.FromSeconds(30)
binding.SendTimeout = TimeSpan.FromSeconds(30)
binding.ReceiveTimeout = TimeSpan.FromSeconds(30)
Dim baseAddress As New Uri($"net.tcp://192.168.1.1:8025/WcfServer")
_serviceHost = New ServiceHost(GetType(WcfServer), baseAddress)
_serviceHost.AddServiceEndpoint(GetType(IWcfServer), binding, baseAddress)
_serviceHost.Open()
在接口上调用方法非常简单:
var binding = new NetTcpBinding();
var url = $"net.tcp://192.168.1.1:8025/WcfServer";
var address = new EndpointAddress(url);
var channelFactory = new ChannelFactory<IWcfServer>(binding, address);
ClientData = channelFactory.CreateChannel();
答案 0 :(得分:0)
默认情况下,Nettcpbinding使用传输安全模式,并且客户端凭据类型为Windows。
因此,我们在调用服务时应在客户端提供Windows凭据。
此外,TCP通讯也受Windows防火墙保护,请关闭防火墙,然后重试。
最后,添加Console.Readline()以防止服务主机自动关闭。
using (ServiceHost sh = new ServiceHost(typeof(MyService)))
{
sh.Open();
Console.WriteLine("serivce is ready....");
Console.ReadLine();
sh.Close();
}
已更新:
服务器端(控制台应用程序)
class Program
{
static void Main(string[] args)
{
using (ServiceHost sh = new ServiceHost(typeof(MyService)))
{
sh.Open();
Console.WriteLine("serivce is ready....");
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
string Test();
}
public class MyService : IService
{
public string Test()
{
return DateTime.Now.ToLongTimeString();
}
}
App.config(服务器)
<system.serviceModel>
<services>
<service name="VM1.MyService">
<endpoint address="" binding="netTcpBinding" contract="VM1.IService" >
</endpoint>
<endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange" ></endpoint>
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:5566"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
客户端。
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("net.tcp://10.157.13.69:5566");
NetTcpBinding binding = new NetTcpBinding();
ChannelFactory<IService> factory = new ChannelFactory<IService>(binding, new EndpointAddress(uri));
factory.Credentials.Windows.ClientCredential.UserName = "administrator";
factory.Credentials.Windows.ClientCredential.Password = "abcd1234!";
IService service = factory.CreateChannel();
try
{
var result = service.Test();
Console.WriteLine(result);
}
catch (Exception)
{
throw;
}
}
}
[ServiceContract]
public interface IService
{
[OperationContract]
string Test();
}
请随时让我知道问题是否仍然存在。