天津投入产出系统后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

161 lines
4.5 KiB

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
{
/// <summary>
/// 双工通讯服务
/// </summary>
public class DuplexMessageService : IDuplexMessageService
{
/// <summary>
/// 客户端会话列表
/// </summary>
public static ConcurrentDictionary<string, ICallBackService> ClientList = new ConcurrentDictionary<string, ICallBackService>();//记录Sessionid
#region 向服务端请求
/// <summary>
/// 向服务端请求
/// </summary>
/// <param name="message"></param>
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<ICallBackService>();
//添加会话信息
ClientList.TryAdd(sessionID, client);
Worker info = QMFrameWork.Common.Serialization.JsonConvertHelper.GetDeserialize<Worker>(message.Content);
//向注册中心注册
RegisterCenter.RegisterWorker(sessionID, clientHostName, info);
}
catch (Exception e)
{
throw new FaultException(e.Message);
}
}
#endregion
#region 客户端断开连接
/// <summary>
/// 客户端断开连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Channel_Closing(object sender, EventArgs e)
{
List<string> sessionList = new List<string>();
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<string, ICallBackService> GetClientList()
{
return ClientList;
}
#endregion
#region 服务端向客户端发送信息(异步)
/// <summary>
/// 服务端向客户端发送信息(异步)
/// </summary>
/// <param name="Message"></param>
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
}
}