using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
namespace Fago.Common.Helper
{
/// <summary>
/// Wcf 客户端辅助类
/// </summary>
public class WcfClientHelper
{
#region 常量
/// <summary>
/// 注册到行情服务器的重试次数
/// </summary>
private const int REGISTER_TO_SERVER_RETRY_COUNT = 3;
/// <summary>
/// 注册到行情服务器的重试间隔(毫秒)
/// </summary>
private const int REGISTER_TO_SERVER_RETRY_INTERVAL = 2000;
/// <summary>
/// 关闭接收客户端的重试次数
/// </summary>
private const int CLOSE_CLIENT_RETRY_COUNT = 3;
/// <summary>
/// 关闭接收客户端的重试间隔(毫秒)
/// </summary>
private const int CLOSE_CLIENT_RETRY_INTERVAL = 1000;
#endregion
/// <summary>
/// 客户端是否可用
/// </summary>
/// <typeparam name="T">客户端类型</typeparam>
/// <param name="client">客户端</param>
/// <returns>是否可用</returns>
public static bool IsAval<T>(ClientBase<T> client) where T : class
{
return client != null
&& client.State == CommunicationState.Opened;
}
/// <summary>
/// 获取可用的客户端
/// </summary>
/// <typeparam name="T">客户端类型</typeparam>
/// <param name="clientType">客户端类型</param>
/// <param name="calllback">回调实例</param>
/// <returns>当前客户端是否可用</returns>
public static ClientBase<T> GetAvalClient<T>(Type clientType, object calllback = null) where T : class
{
if (clientType == null)
{
return null;
}
try
{
ClientBase<T> client = (calllback != null
? Activator.CreateInstance(clientType, new InstanceContext(calllback)) // 具有回调接口的服务
: Activator.CreateInstance(clientType)) // 不具有回调接口的服务
as ClientBase<T>;
client.Open();
int iRetryCount = 0; // 重试次数
while (iRetryCount++ < REGISTER_TO_SERVER_RETRY_COUNT)
{
if (client.State != CommunicationState.Opened)
{
// 如果基础运算对象状态为非打开状态(不能正常通信),则终止此对象
client.Abort();
// 弃用原来的对象,再新建一个并打开
client = (calllback != null
? Activator.CreateInstance(clientType, new InstanceContext(calllback)) // 具有回调接口的服务
: Activator.CreateInstance(clientType)) // 不具有回调接口的服务
as ClientBase<T>;
client.Open();
}
if (client.State == CommunicationState.Opened)
{
break;
}
Thread.Sleep(REGISTER_TO_SERVER_RETRY_INTERVAL);
}
return client.State == CommunicationState.Opened ? client : null;
}
catch (Exception ex)
{
Debug.WriteLine("向服务器注册客户端失败:" + ex.Message);
return null;
}
}
/// <summary>
/// 安全关闭客户端
/// </summary>
/// <typeparam name="T">客户端类型</typeparam>
/// <param name="client">客户端</param>
/// <returns>是否成功</returns>
public static bool SafeCloseClient<T>(ClientBase<T> client) where T : class
{
if (client == null
|| client.State == CommunicationState.Closed)
{
return true;
}
try
{
client.Close();
int iRetryCount = 0; // 重试次数
while (iRetryCount++ < CLOSE_CLIENT_RETRY_COUNT
&& client.State != CommunicationState.Closed)
{
// 终止此对象
client.Abort();
// 延迟
Thread.Sleep(CLOSE_CLIENT_RETRY_INTERVAL);
}
return client.State == CommunicationState.Closed;
}
catch (Exception ex)
{
Debug.WriteLine("关闭客户端失败:" + ex.Message);
return false;
}
}
}
}