学习WCF相关知识,写一段WCF的小代码,客户端调用本地写好的WCF时提示:”操作超时”,也按照网上的说法修改.
如:
1、首先保证客户端每次建立的连接在使用完成后进行关闭.即调用Close方法,否则此连接会在设置的会话后才自动关闭(该自动响应时间一般为10分钟,InactivityTimeOut属性),期间任何客户端也无法使用此服务.
2、可以增加默认连接连接数.配置文件如下:< serviceThrottling maxConcurrentCalls=”20″ maxConcurrentSessions=”20″ maxConcurrentInstances=”30″ />
说明:maxConcurrentCalls :最大并发数,默认为16;maxConcurrentSessions :最大的会话数,主要针对于PerSession的情况,默认为10;maxConcurrentInstances:最大实例数,默认为26
但真的解决不了问题.搞了半天总算找到了真正的原因.
下面小程序代码如下:
先在“引用”添加引用 System.ServiceModel;
类库 Iservice 中接口文件:ifly.cs
using System.ServiceModel;
namespace Iservice
{
[ServiceContract]
public interface ifly
{
[OperationContract]
string peofly(string name);
}
}
类库 service 中类文件:fly.cs
using System.ServiceModel;
using Iservice;
namespace service
{
public class fly:ifly
{
public string peofly(string name)
{
return "name:" + name;
}
}
}
控制台应用程序 host 中Program.cs
using System.ServiceModel;
using Iservice;
using service;
namespace host
{
class Program
{
static void Main(string[] args)
{
using(ServiceHost host=new ServiceHost(typeof(service.fly)))
{
host.Open();
Console.WriteLine("Start...");
Console.Read();
host.Close();//这一步运行不到吧!!!
}
}
}
}
在控制台应用程序 host 中添加 配置文件 App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<!--service 类库命名空间,fly 类名-->
<service name="service.fly" behaviorConfiguration="MessageBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:1111/a"/>
</baseAddresses>
</host>
<!--Iservice 类库命名空间,ifly 接口名-->
<!--wsHttpBinding,这个binding可以认为是webservice的加强版WSE,设计的目的就是用于异构系统的交互(比如java)-->
<endpoint address="" binding="wsHttpBinding" contract="Iservice.ifly"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="MessageBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<!--这一行没用-->
<!--<serviceThrottling maxConcurrentCalls="200" maxConcurrentSessions="1000" maxConcurrentInstances="50000"/>-->
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
生成之后 在 host\bin\Debug文件夹下 用“管理员权限”打开host.exe
在客户端 控制台应用程序中 test 引用服务
右键=>添加服务引用=>输入地址 http://localhost:1111/a,修改命名空间为 sr
test的Program.cs添加代码:
namespace test
{
class Program
{
static void Main(string[] args)
{
sr.iflyClient si = new sr.iflyClient();
Console.Write(si.peofly("ls"));
Console.Read();
}
}
}
将test设为启动项
Ctrl+F5运行:
控制台弹出:name:ls
运行正常。
开始的时候之所以提示 “操作超时”,与我添加服务的方式有关:
开始时添加服务方式:
右键=>添加服务引用=>右下角“高级”=>右下角“添加Web引用”=>输入地址 http://localhost:1111/a,修改命名空间为 sr
namespace test
{
class Program
{
static void Main(string[] args)
{
sr.fly si = new sr.fly();
Console.Write(si.peofly("ls"));
Console.Read();
}
}
}
这样就会出现标题的错误.
在这里,引用之后发现两个不同之处,我想应该就是错误原因:
1:没看到什么区别。。。。。。很纠结。。。。。。
正确:
sr.iflyClient si = new sr.iflyClient();
错误:
sr.fly si = new sr.fly();
2.
正确的添加后是 Service References
错误的添加后是 Web References
如图:
难道本机写的WCF在本机发布 不能使用 高级 引用菜单。实验了一下引用网上的WCF服务,果然如此,网上发布的免费WCF,只能在 高级 引用菜单里引用才能正确调用。
update:2019-01-14 修正代码高亮