Exemplo n.º 1
0
        /// <summary>
        /// Sends packets from the queue.
        /// This must be started on a thread, as it will block until CommHandler.Stopping is true.
        /// Assumes that packets will not be removed from SendQueue anywhere but inside this method.
        /// </summary>
        private static void SendPackets()
        {
            if (!Initialized)
            {
                throw new InvalidOperationException("Cannot use CommHandler before initialization. Call CommHandler.Start().");
            }
            while (!Stopping)
            {
                foreach (PacketBuffer SendQueue in SendQueues.Values)
                {
                    Packet ToSend = SendQueue.Dequeue();
                    if (ToSend != null)
                    {
                        try
                        {
                            SendNow(ToSend);
                        }
                        catch (Exception Exc)
                        {
                            Log.Output(Log.Severity.WARNING, Log.Source.NETWORK, "Failed to send packet.");
                            Log.Exception(Log.Source.NETWORK, Exc);
                        }
                    }
                }

                // Wait for operation period
                Thread.Sleep(OperationPeriod);
            }
        }
Exemplo n.º 2
0
    /** 将消息队列中包发送出去 */
    private void SendPacket()
    {
        try
        {
            // 发送当前队列所有消息包
            while (SendQueue.Count > 0)
            {
                byte[] msg = SendQueue.Dequeue();

                #region SS
                //Packet packet = new Packet(ServerDataType.protobuf, true);
                //packet.Decode(msg);
                //Debug.Log("packed ID = " + packet.Header.PacketID);
                //if (packet.Header.PacketID == 2002 || packet.Header.PacketID == 2004)
                //{
                //	GameLog.LogCtrl.Info("{0} time {1}", packet.Header.PacketID, FacadeGlobal.TimerCtrl.GetTimeStamp());
                //}

                //if (packet.Header.PacketID == 307)
                //{
                //	GameLog.LogCtrl.Info("{0} time {1}", packet.Header.PacketID, FacadeGlobal.TimerCtrl.GetTimeStamp());
                //}
                #endregion

                _Socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, SendCallback, _Socket);
                //_Socket.Send(msg);
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Send Message Failed: " + e.ToString());
        }
    }
Exemplo n.º 3
0
        private void SendLoop()
        {
            while (true)
            {
                if (_sendQueue.IsEmpty() == false)
                {
                    Client client   = new Client(ActiveConnection, _logger);
                    var    nextFile = _sendQueue.Front();

                    // don't send a file that we are currently receiving.  Instead,
                    //wait for file to complete before sending.
                    if (_receivingFiles.ContainsKey(nextFile.Path) == false)
                    {
                        var result = client.SendFile(nextFile);
                        if (result.WasSuccessful == true)
                        {
                            lock (_sendQueue)
                            {
                                _sendQueue.Dequeue();
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(100);
                    }
                }
                else
                {
                    Thread.Sleep(100);
                }
            }
        }
Exemplo n.º 4
0
 private void ReSendMessage()
 {
     if (SendQueue.Count > 0 && AppUtil._SocketFirstOutConnected)
     {
         string sendmessage = SendQueue.Dequeue();
         SendMessage(FirstOut, sendmessage);
     }
 }
Exemplo n.º 5
0
        public void DequeueTest()
        {
            SendQueue  target   = new SendQueue();  // TODO: 初始化为适当的值
            SendBuffer expected = new SendBuffer(); // TODO: 初始化为适当的值
            SendBuffer actual;

            actual = target.Dequeue();
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("验证此测试方法的正确性。");
        }
Exemplo n.º 6
0
 public override void Tick(uint tick)
 {
     if (SendQueue.Count != 0)
     {
         OtherEnd.RecievePacket(SendQueue.Dequeue());
         Log("Packet sent from" + sysID + "to" + OtherEnd.sysID);
     }
     if (RecieveQueue.Count != 0)
     {
         CallOnRecievedPacket(RecieveQueue.Dequeue(), this);
     }
 }
Exemplo n.º 7
0
        private async Task SendMessages()
        {
            for (int i = 0; i < 5 && SendQueue.Count > 0; i++)
            {
                var details = SendQueue.Dequeue();

                details.SentAt = Stopwatch.StartNew();
                if (details.Message is QueryMessage)
                {
                    WaitingResponse.Add(details.Message.TransactionId, details);
                }

                byte[] buffer = details.Message.Encode();
                await Listener.SendAsync(buffer, details.Destination);
            }
        }
Exemplo n.º 8
0
 public override void Tick(uint tick)
 {
     Log("Group adapt.Tick");
     if (SendQueue.Count != 0)
     {
         byte[] packet = SendQueue.Dequeue();
         foreach (NetworkInterface n in OtherEnds.Values)
         {
             n.RecievePacket(packet);
             Log("Paket sent from" + sysID + "to" + n.sysID);
         }
     }
     if (RecieveQueue.Count != 0)
     {
         CallOnRecievedPacket(RecieveQueue.Dequeue(), this);
     }
 }
Exemplo n.º 9
0
        async Task SendMessages()
        {
            for (int i = 0; i < 5 && SendQueue.Count > 0; i++)
            {
                SendDetails details = SendQueue.Dequeue();

                details.SentAt = ValueStopwatch.StartNew();
                if (details.Message is QueryMessage)
                {
                    WaitingResponse.Add(details.Message.TransactionId, details);
                }

                byte[] buffer = details.Message.Encode();
                try {
                    Monitor.SendMonitor.AddDelta(buffer.Length);
                    await Listener.SendAsync(buffer, details.Destination);
                } catch {
                    TimeoutMessage(details);
                }
            }
        }
Exemplo n.º 10
0
 void ProcessSender()
 {
     try
     {
         do
         {
             mreSender.WaitOne();
             if (!abort)
             {
                 if (ServerStream != null)
                 {
                     while (SendQueue.Count > 0)
                     {
                         if (_log.IsInfoEnabled)
                         {
                             _log.Info("Sending data to server");
                         }
                         byte[] buff = SendQueue.Dequeue();
                         ServerStream.Write(buff, 0, buff.Length);
                     }
                 }
             }
             if (!abort)
             {
                 mreSender.Reset();
             }
         } while (!abort);
     }
     catch (ThreadAbortException)
     {
     }
     catch (SocketException e)
     {
         if (_log.IsWarnEnabled)
         {
             _log.Warn("Exception from socket", e);
         }
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// 自动执行发送消息的任务.
        /// </summary>
        /// <param name="myQQ"></param>
        private void StartTask(string myQQ)
        {
            if (_QQMap.ContainsKey(myQQ) && _SendMap.ContainsKey(myQQ))
            {
                SendQueue sq   = _SendMap[myQQ];
                WebQQ     qq   = _QQMap[myQQ];
                Task      tast = new Task(() =>
                {
                    SendMsg sm;
                    while (true)
                    {
                        if (sq.Dequeue(out sm))
                        {
                            bool result = false;
                            for (int i = 0; i < 3; i++)
                            {
                                if (qq.SendMessage(sm.FriendQQ, sm.Context, new Font("宋体", 12F), Color.Black))
                                {
                                    result = true;
                                    break;
                                }
                            }
                            if (!result)
                            {
                                if (SendError != null)
                                {
                                    SendError(myQQ, sm.FriendQQ, sm.Context);
                                }
                            }
                        }
                        Thread.Sleep(200);
                    }
                }
                                          );

                tast.Start();
            }
        }
Exemplo n.º 12
0
    private void SendData()
    {
        if (SendQueue.Count <= 0)
        {
            return;
        }
        // Packet sendPackage = mSendQueue.Dequeue();
        // byte[] data = sendPackage.GetBytes();
        byte[] data = SendQueue.Dequeue();
        mWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        mWebClient.Headers.Add("ContentLength", data.Length.ToString());

        try
        {
            mWebClient.UploadDataAsync(mUrl, data);
        }
        catch (System.Exception e)
        {
            Debug.LogError("HttpObject SendData Exception: " + e.Message);
        }

        IsReadySend = false;
    }
Exemplo n.º 13
0
        private void ProcessReply(string line)
        {
            App.ViewModel.AddDebugLog(string.Format("<{0}", line));
            var pattern = "^([A-Z]+)([:][A-Z0-9_]+)?(|.+)?$";
            var match   = Regex.Match(line, pattern);

            if (match.Success)
            {
                var     command   = match.Groups[1].Value;
                var     parameter = string.IsNullOrEmpty(match.Groups[2].Value) ? null : match.Groups[2].Value.Substring(1);
                var     addict    = string.IsNullOrWhiteSpace(match.Groups[3].Value) ? null : match.Groups[3].Value.Substring(1).Trim();
                dynamic json      = string.IsNullOrEmpty(addict) ? null
                                        : JsonConvert.DeserializeObject <dynamic>(addict, new JsonSerializerSettings {
                    Error = (s, e) => { e.ErrorContext.Handled = true; }
                });
                if (json == null)
                {
                    json = JsonConvert.DeserializeObject <dynamic>("{}");
                }

                switch (command)
                {
                case "BYE":
                    Transport.Shutdown(SocketShutdown.Both);
                    Transport.Close();
                    break;

                case "G":
                    foreach (var c in (json as JArray).Cast <JValue>().Select(s => s.Value.ToString().Split('|')).ToList())
                    {
                        Do(() => { App.ViewModel.GroupsModel.AddCoordinate(c[0], Coordinate.Create(c[1])); });
                    }
                    break;

                case "GA":
                    CGroup();
                    break;

                case "GD":
                    CGroup();
                    break;

                case "GE":
                    CGroup();
                    break;

                case "GP":
                    var group = JsonConvert.DeserializeObject <Group>(addict);
                    Do(() => { App.ViewModel.GroupsModel.SetUsers(parameter, group.Users); });
                    CGpr(parameter);
                    break;

                case "GPR":
                    break;

                case "GROUP":
                    Do(() => { lock (App.ViewModel.GroupsModel.Groups) { App.ViewModel.GroupsModel.Groups = JsonConvert.DeserializeObject <List <Group> >(addict); } });
                    break;

                case "INIT":
                    if (json["error"] != null)
                    {
                        Disconnect();
                    }
                    else
                    {
                        Do(() => { App.ViewModel.TrackerId = ((JValue)json["id"]).ToObject <string>(); });
                        CMd();
                    }
                    break;

                case "MD":
                    Status = ConnectionStatus.Connected;
                    while (SendQueue.Count > 0)
                    {
                        Send(SendQueue.Dequeue());
                    }
                    Do(() => { App.ViewModel.MessageOfTheDay = addict; });
                    break;

                case "P":
                    break;

                case "PP":
                    CP();
                    break;

                case "RC":
                    break;

                case "TO":
                    Do(() => { App.ViewModel.SessionId = ((JValue)json["url"]).ToObject <string>(); });
                    break;

                case "T":
                    break;

                case "TC":
                    Do(() => { App.ViewModel.SessionId = null; });
                    break;

                default:
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                    break;
                }
            }
        }