using Muchinfo.MTPClient.Data.Enums;
using Muchinfo.MTPClient.Infrastructure.Helpers;
using Muchinfo.MTPClient.NetworkCore;
using System;
namespace Muchinfo.MTPClient.Infrastructure.LinkProxy.TCP
{
///
/// 业务代理连接
///
public class TradeTcpLinkProxy : IDisposable
{
public string _host; ////主机地址
public int _port; ////通信端口号
private TCPManager _tcpManager;
public TCPConnectState TcpConnectState
{
get { return (_tcpManager == null) ? TCPConnectState.Closed : _tcpManager.tcpConnectState; }
}
///
/// 创建业务连接
///
public TradeTcpLinkProxy(string host, int port)
{
_host = host;
_port = port;
_tcpManager = new TCPManager(DatagramType.Datagram50, new TradeTcpCallback(this));
LogInfoHelper.WriteInfo("开始连接交易服务..");
_tcpManager.Connect(_host, _port, ConnectSuccess, ConnectFail);
}
///
/// 连接失败
///
/// 错误码
/// 连接描述
private void ConnectFail(int errorCode, string desc)
{
//todo:通知连接失败
LogInfoHelper.WriteInfo("交易务连接失败![" + errorCode + "] " + desc);
MessengerHelper.DefaultSend(false, MessengerTokens.TradeCreateConnect);
}
///
/// 连接成功
///
private void ConnectSuccess()
{
//todo:通知连接成功
LogInfoHelper.WriteInfo("交易服务连接成功!");
MessengerHelper.DefaultSend(true, MessengerTokens.TradeCreateConnect);
}
///
/// 发送消息,
///
/// 消息内容
/// 成功回复
/// 错误回复
public void SendPackage(TCPPackage package, Action successAction, Action failAction)
{
if (_tcpManager == null)
{
//todo:抛异常
return;
}
_tcpManager.SendMessage(package, successAction, failAction);
}
///
/// 通知通信组件开始发送心跳的方法
///
public void StartSendBeat()
{
if (_tcpManager == null)
{
//todo:抛异常
return;
}
LogInfoHelper.WriteInfo("交易登录成功,启动发送心跳包!");
_tcpManager.StartSendBeats();
}
///
/// 执行与释放或重置非托管资源相关的应用程序定义的任务。
///
public void Dispose()
{
if (_tcpManager != null)
{
_tcpManager.Disconnect();
_tcpManager = null;
}
}
///
/// 设置断线重连标志
///
public void SetReconnectFlag(bool flag)
{
if (null != _tcpManager) _tcpManager.SetReconnectFlag(flag);
}
}
}