using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using QM.Exchange.Interface;
using QM.Exchange.Core.Services;
namespace QM.Exchange.Core
{
///
/// 双工通讯服务
///
public class DuplexMessageService : IDuplexMessageService
{
///
/// 客户端会话列表
///
public static ConcurrentDictionary ClientList = new ConcurrentDictionary();//记录Sessionid
#region 向服务端请求
///
/// 向服务端请求
///
///
public void RequestServer(CommonMessage message)
{
try
{
OperationContext.Current.Channel.Closing += new EventHandler(Channel_Closing);
string sessionID = OperationContext.Current.SessionId;
if (ClientList.ContainsKey(sessionID) == false)
{
//注册
this.Register(sessionID, message);
}
else
{
//其他处理
MessageQueueService.Enqueue(message);
}
}
catch (Exception e)
{
throw new FaultException(e.Message);
}
}
#endregion
#region 注册
private void Register(string sessionID, CommonMessage message)
{
try
{
string clientHostName = OperationContext.Current.Channel.RemoteAddress.Uri.Host;
ICallBackService client = OperationContext.Current.GetCallbackChannel();
//添加会话信息
ClientList.TryAdd(sessionID, client);
Worker info = QMFrameWork.Common.Serialization.JsonConvertHelper.GetDeserialize(message.Content);
//向注册中心注册
RegisterCenter.RegisterWorker(sessionID, clientHostName, info);
}
catch (Exception e)
{
throw new FaultException(e.Message);
}
}
#endregion
#region 客户端断开连接
///
/// 客户端断开连接
///
///
///
void Channel_Closing(object sender, EventArgs e)
{
List sessionList = new List();
try
{
foreach (var d in ClientList)
{
if (d.Value == (ICallBackService)sender)//删除此关闭的会话信息
{
ICallBackService outValue = null;
ClientList.TryRemove(d.Key, out outValue);
sessionList.Add(d.Key);
break;
}
}
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
finally
{
//注销工作节点
RegisterCenter.LogoffWorker(sessionList);
}
}
#endregion
#region 获取客户端会话列表
public ConcurrentDictionary GetClientList()
{
return ClientList;
}
#endregion
#region 服务端向客户端发送信息(异步)
///
/// 服务端向客户端发送信息(异步)
///
///
public void SendMessageToClient(string sessionID, CommonMessage message)
{
try
{
ICallBackService client = null;
bool r = ClientList.TryGetValue(sessionID, out client);
if (r == true)
{
client.SendMessageToClient(message);
}
else
{
//客户端已离线
Console.WriteLine("sessionID:" + sessionID + "的客户端已下线");
}
}
catch (Exception e)
{
throw new FaultException(e.Message);
}
}
#endregion
}
}