三种交换模式(本链接三种模式的例子):One-Way Calls、Request/Reply、Duplex。
1、One-Way Calls
这个相当与单向的客户端向服务端发请求,服务端不做任何操作。
代码案例:
服务:
[ServiceContract]
public interface IOneWayJob
{
/// <summary>
/// 单项通讯模式,Isoneway=true,不能有返回值,而且参数不能包含ref/out
/// </summary>
/// <param name="jobName"></param>
[OperationContract(IsOneWay=true)]
void Do(string jobName);
}
实现:
public class OneWayJob : IOneWayJob
{
public void Do(string jobName)
{
System.Diagnostics.Stopwatch watcher = new System.Diagnostics.Stopwatch();
watcher.Start();
System.Threading.Thread.Sleep(1000);
Console.WriteLine("服务" + AppDomain.CurrentDomain.FriendlyName + "执行任务:" + jobName);
watcher.Stop();
}
}
寄宿:
class Program
{
static void Main(string[] args)
{
try
{
Uri tcpAddress = new Uri("net.tcp://localhost:6887/Service");
ServiceHost oneWayHost = new ServiceHost(typeof(OneWayJob), tcpAddress);
oneWayHost.Open();
Console.WriteLine("服务已启动。。。");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
}
配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="Service.OneWayJob">
<endpoint name="OneWayJobService" address="oneways" binding="netTcpBinding" contract="Contract.IOneWayJob">
<identity>
<dns value="localHost"></dns>
</identity>
</endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
客户端控制台程序:
static void Main(string[] args)
{
Console.WriteLine("开始调用");
using (ChannelFactory<IOneWayJob> channelFactory = new ChannelFactory<IOneWayJob>("OneWayJobService"))
{
IOneWayJob proxy = channelFactory.CreateChannel();
proxy.Do("oneWay");
}
Console.WriteLine("调用结束");
}
客户端的xml:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="netTcpBinding"></binding>
</netTcpBinding>
</bindings>
<endpoint address="net.tcp://localhost:6887/Service/oneways" binding="netTcpBinding" bindingConfiguration="netTcpBinding" contract="Contract.IOneWayJob" name="OneWayJobService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
</client>
</system.serviceModel>
</configuration>
单项的比较简单,除了服务注意下面这句话加上,其他并没有任何的影响。
[OperationContract(IsOneWay=true)]