利用WCF双工模式实现即时通讯

2019-12-30 14:05:38王冬梅

概述 

WCF陆陆续续也用过多次,但每次都是浅尝辄止,以将够解决问题为王道,这几天稍闲,特寻了些资料看,昨晚尝试使用WCF的双工模式实现了一个简单的即时通讯程序,通过服务端转发实现客户端之间的通讯。这只是个Demo,没有考虑异常处理和性能问题。解决方案结构如下:

WCF,双工模式,即时通讯

契约


using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace Service.Interface
{
 [ServiceContract(CallbackContract = typeof(ICallBack))]
 public interface INoticeOperator
 {
 [OperationContract]
 void Register(String id);

 [OperationContract]
 void UnRegister(String id);

 [OperationContract]
 void SendMessage(String from, String to, String message);
 }
} 

该接口定义了三个行为,分别是:

 •注册
 •注销
 •发消息 

其中,在特性[ServiceContract(CallbackContract = typeof(ICallBack))]中指定了用于服务端回调客户方法的契约ICallBack,其定义如下:


 using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace Service.Interface
{
 public interface ICallBack
 {
 [OperationContract(IsOneWay = true)]
 void Notice(String message);
 }
} 

实体 

本Demo只有一个实体,用来表示已经注册用户的Id和对应的回调契约的具体实现的实例:


using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Models
{
 public class Client
 {
 public String Id { get; set; }

 public ICallBack CallBack { get; set; }
 }
} 

契约的实现代码


 using Models;
using Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
 public class NoticeOperator : INoticeOperator
 {
 private static List<Client> clientList = new List<Client>();

 public void Register(string id)
 {
  Console.WriteLine("register:" + id);

  ICallBack callBack = OperationContext.Current.GetCallbackChannel<ICallBack>();
  clientList.Add(new Client() { Id = id, CallBack = callBack });
 }

 public void UnRegister(string id)
 {
  Console.WriteLine("unRegister:" + id);

  Client client = clientList.Find(c => c.Id == id);
  if (client != null)
  {
  clientList.Remove(client);
  }
 }

 public void SendMessage(string from, string to, string message)
 {
  Client client = clientList.Find(c => c.Id == to);
  if (client != null)
  {
  String longMessage = String.Format("message from {0} to {1} at {2} : {3}", from, to, DateTime.Now.ToString("HH:mm:ss"), message);
  Console.WriteLine(longMessage);
  client.CallBack.Notice(longMessage);
  }
 }
 }
}