123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using CommonNetwork_ICE.Util;
- using CommonNetwork_ICE.Common;
- using Slice;
- using CommonLang.Log;
- namespace CommonNetwork_ICE.Msg
- {
- /// <summary>
- /// 客户端消息包循环发送处理类
- /// </summary>
- public class ClientMessageQueue
- {
- private static Logger log = LoggerFactory.GetLogger("ClientMessageQueue");
- // 待发送消息队列
- private static Queue<TransMessage> queue = new Queue<TransMessage>();
- // 消息队列绑定线程
- private Thread thread;
- // 是否运行线程
- private bool runFlag;
- // 发送的数据包序列号
- private long sentSerial;
- // 超时时间
- private int timeout = Env.SEND_WAIT_ACK_TIME_OUT;
- public ClientMessageQueue()
- {
- this.sentSerial = 0;
- this.LastSerial = 0;
- }
- // 发送接口
- public IceConnector Connector { get; set; }
- // 服务器返回的数据包序列号
- public long LastSerial { set; get; }
- public void Start()
- {
- thread = new Thread(Run);
- runFlag = true;
- thread.Start();
- }
- public void End()
- {
- runFlag = false;
- if (thread != null)
- {
- thread.Join();
- thread.Abort();
- }
- }
- /// <summary>
- /// 加入新消息
- /// </summary>
- /// <param name="message"></param>
- public void AddMessage(TransMessage message)
- {
- queue.Enqueue(message);
- }
- /// <summary>
- /// 消息发送
- /// </summary>
- private void Run()
- {
- TransMessage preMessage = null;
- DateTime preDateTime = DateTime.Now;
- while (runFlag || queue.Count > 0)
- {
- try
- {
- // 当前发送数据包的应答序号号未收到
- if (sentSerial != LastSerial)
- {
- // 是否在发送超时时间内
- if (preDateTime.AddSeconds(timeout) < DateTime.Now)
- {
- if (preMessage != null)
- {
- try
- {
- Connector.Sender.SendData(Connector.GetConnectorConfig().LocalPort, preMessage);
- }
- catch (Exception e)
- {
- log.Error("客户端重发数据错误:" + e.Message);
- continue;
- }
- log.Trace("没收到关键包应答,客户端重发数据:" + preMessage.serial);
- preDateTime = DateTime.Now;
- }
- continue;
- }
- else
- {
- log.Trace("没收到关键包应答,等待当前序列号数据包:" + sentSerial);
- Thread.Sleep(Env.SEND_WAIT_ACT_THREAD_SLEEP_TIME);
- continue;
- }
- }
- if (queue.Count > 0)
- {
- // 发送数据包
- TransMessage outMessage = queue.Dequeue();
- try
- {
- Connector.Sender.SendData(Connector.GetConnectorConfig().LocalPort, outMessage);
- }
- catch (Exception e)
- {
- log.Error("消息循环发送数据错误:" + e.Message);
- continue;
- }
- preDateTime = DateTime.Now;
- // 如果是关键数据包,记录序列号,进入下一个发送周期
- if (outMessage.type == Constants.PACKET_HINGE)
- {
- sentSerial = outMessage.serial;
- preMessage = outMessage;
- }
- }
- }
- catch (Exception err)
- {
- log.Error(err.Message, err);
- }
- }
- }
- }
- }
|