Register方法用来把Client实体加入到一个列表中,模拟注册行为,Clinet实体包含了用户信息和实现了回调契约的一个实例对象。
UnRegister方法用来把一个Client从列表中移除,模拟注销行为。
SendMessage方法用来发送消息,第一个参数是发送者的Id,第二个参数是消息接受者的Id,第三个参数是发送内容,该方法先将消息在服务端打印出来,然后再回调消息接收者对应的回调契约的具体实现类的实例对象的Notice方法以达到服务端向客户端发送消息的目的。
宿主
using Service;
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;
namespace Hosting
{
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(NoticeOperator)))
{
host.AddServiceEndpoint(typeof(INoticeOperator), new NetTcpBinding(), "net.tcp://127.0.0.1:9527/NoticeOperator");
host.Opened += (s, e) => Console.WriteLine("service is running...");
host.Open();
Console.ReadLine();
}
}
}
}
宿主是一个控制台应用程序,使用的绑定类型为NetTcpBinding,端口是华安的华府的终生代号。
客户端代码
实现回调接口
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class CallBack : ICallBack
{
public void Notice(string message)
{
Console.WriteLine(message);
}
}
}
模拟注册,发消息和注销
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
InstanceContext context = new InstanceContext(new CallBack());
using (ChannelFactory<INoticeOperator> factory = new DuplexChannelFactory<INoticeOperator>(context, new NetTcpBinding(), "net.tcp://127.0.0.1:9527/NoticeOperator"))
{
INoticeOperator proxy = factory.CreateChannel();
String selfId = args[0];
String friendId = args[1];
proxy.Register(selfId);
Console.WriteLine("----------Register------------");
while(true)
{
String message = Console.ReadLine();
if (message == "q")
{
proxy.UnRegister(selfId);
break;
}
else
{
proxy.SendMessage(selfId, friendId, message);
}
}
}
}
}
}
在CMD中运行test.exe Joey Ross表示Joey注册,要给他的朋友Ross发送消息;再起一个进程test.exe Ross Joey表示Ross注册,要给他的朋友Joey发送消息。进程启动后输入一些字符按回车即发送至了对方,输入q回车注销并退出程序。如下图所示:










