示例#1
0
 public MessageTypeError(EMessage type, INodeComponent connect = null)
     :
     base("Error Message Type: " + type + ", Connect:" + connect)
 {
 }
        /// <summary>
        /// watch dog has the highest authority in agent, it performs some light weight operations, such as update 'TCounters'
        /// </summary>
        private void __threadWatchdog(ThreadControl control)
        {
            logger.Debug($"{nameof(__threadWatchdog)}() on duty.");

            var feedCycle      = Math.Min(1000, this.timeout >> 1); // the cycle of dog feeding, unit: ms
            var feedTCounter   = 0;
            var msg            = new EMessage(0);
            var foodBag        = new[] { DOG_FOOD_FLAG };
            var threadInterval = 1;  // watch dog scan cycle, ms

            while (!control.SafelyTerminating)
            {
                Thread.Sleep(threadInterval);

                // -1 denote that the dog is dead,only __threadListen can set it back to '0' to rebirth the dog
                if (watchDog == -1)
                {
                    continue;                  // no more actions when dog has died
                }

                /*******************
                * update TCounters
                * *****************/
                KeyValuePair <uint, TCounter>[] msgIdAndTCounterPairs;
                lock (dictMsgId2TC) msgIdAndTCounterPairs = dictMsgId2TC.ToArray();
                foreach (var kv in msgIdAndTCounterPairs)
                {
                    if (kv.Value.Decrease(threadInterval) || !this.IsConnected) // request timeout
                    {
                        kv.Value.CountDown = 0;                                 // set countdown to 'timeout'
                        RemoveWaitFlag(kv.Key);
                        ThreadPool.QueueUserWorkItem(_processTimeoutMessage, kv.Value.RequestMsg);
                    }
                }

                /************
                * watch dog
                * **********/
                if (IsConnected)
                {
                    // check local dog
                    watchDog += threadInterval;
                    if (watchDog >= timeout)
                    {
                        watchDog = -1;  // time out flag

                        GetControl(ThreadType.Listen).SafeAbort();
                        OnConnectionTimeout();
                        logger.Error($"{this} connection timeout.");
                    }

                    // feed remote dog
                    feedTCounter += threadInterval;
                    if (feedTCounter >= feedCycle)
                    {
                        feedTCounter = 0;  // reset

                        try
                        {
                            SendBytes(foodBag, 0, foodBag.Length);
                        }
                        catch
                        {
                            // pass, ignore all errors
                        }
                    }
                }
            }

            control.SetAbortedFlags();

            logger.Debug($"{nameof(__threadWatchdog)}() aborted.");

            this.Destroy();
            this.Phase = ConnectionPhase.P0Start;
        }
 /// <summary>
 /// Renders a jQuery UI alert
 /// </summary>
 /// <param name="html">HtmlHelper extension</param>
 /// <param name="type">Type of alert</param>
 /// <param name="message">Alert message</param>
 /// <param name="title">Title/Heading of the alert</param>
 /// <param name="icon">Icon to be rendered with title/heading</param>
 /// <param name="htmlAttributes">[Optional] Any extras HTML attributes to be applied.
 /// Note. These attributes are only applied to the top level div</param>
 /// <returns>A jQuery UI styled alert</returns>
 public static Alert Alert(this HtmlHelper html, EMessage type, string message, string title, EJQueryUIIcon?icon, object htmlAttributes = null)
 {
     return(new Alert(type, message, title, icon, htmlAttributes));
 }
 /// <summary>
 /// process the request sent from remote agent, overrides shoud edit the 'msg', after to process is completed,
 /// <para>the edited message will be treated as response message which will be sent to the remote agent, use StatusCode 'NoAutoReply' to cancell this auto reply action</para>
 /// <para>warning:do not block this method, otherwise program might encounter a connection timeout error due to that the response is not sent to remote agent in time</para>
 /// </summary>
 /// <param name="msg"></param>
 protected abstract void ProcessRequest(ref EMessage msg);
 /// <summary>
 /// process the request message which is timeout
 /// </summary>
 /// <param name="requestMsg"></param>
 protected abstract void ProcessTimeoutRequest(EMessage requestMsg);
示例#6
0
 private MessageBase ParseParameterToMessage(string message, object parameter, out short id)
 {
     MessageBase msgToSend = null;
     if (parameter == null) {
         id = DispatchEMessageId;
         EMessage emsg = new EMessage ();
         emsg.message = message;
         msgToSend = emsg;
     } else if (parameter is int) {
         id = DispatchIMessageId;
         IMessage imsg = new IMessage ();
         imsg.message = message;
         imsg.parameter = (int)parameter;
         msgToSend = imsg;
     } else if (parameter is float) {
         id = DispatchFMessageId;
         FMessage fmsg = new FMessage ();
         fmsg.message = message;
         fmsg.parameter = (float)parameter;
         msgToSend = fmsg;
     } else if (parameter is string) {
         id = DispatchSMessageId;
         SMessage smsg = new SMessage ();
         smsg.message = message;
         smsg.parameter = parameter as string;
         msgToSend = smsg;
     } else if (parameter is Vector3) {
         id = DispatchVMessageId;
         VMessage vmsg = new VMessage ();
         vmsg.message = message;
         vmsg.parameter = (Vector3)parameter;
         msgToSend = vmsg;
     } else if (parameter is Quaternion) {
         id = DispatchQMessageId;
         QMessage qmsg = new QMessage ();
         qmsg.message = message;
         qmsg.parameter = (Quaternion)parameter;
         msgToSend = qmsg;
     } else {
         id = -1;
         Debug.LogError ("Can't dispatch a non RPCable parameter");
     }
     return msgToSend;
 }
 /// <summary>
 /// response to a request
 /// </summary>
 /// <param name="msg"></param>
 protected void Response(EMessage msg)
 {
     msg.Status |= StatusCode.Response;
     SendMessage(msg);
 }
示例#8
0
 private void OnB2C_COMMAND(EMessage msg, Stream buff)
 {
 }
示例#9
0
 /// <summary>
 ///   ControllerBase extension method to save the last action message to the Controller.TempData session store using the
 ///   key denoted by
 ///   'TempDataMessageKey' variable.
 /// </summary>
 /// <param name="c">The controller</param>
 /// <param name="message">The action message to display</param>
 /// <param name="type">Action message type</param>
 /// <param name="args">Any message formatting arguments</param>
 public static void SaveLastActionMessage(this ControllerBase c, string message, EMessage type, params object[] args)
 {
     // store data in temp key, will be alive for one request only
     c.TempData[TempDataMessageKey]     = string.Format(message, args);
     c.TempData[TempDataMessageTypeKey] = type;
 }
示例#10
0
 private void OnB2C_LOAD_PROGRESS(EMessage msg, Stream buff)
 {
 }
示例#11
0
 private void OnB2C_ALL_LOADED(EMessage msg, Stream buff)
 {
 }
示例#12
0
 public Telegram(EMessage Message, GameObject Sender)
 {
     this.Message = Message;
     this.Sender  = Sender;
 }
示例#13
0
 /// <summary>
 ///   Renders a Gumby alert
 /// </summary>
 /// <param name="html">HtmlHelper extension</param>
 /// <param name="type">Type of alert</param>
 /// <param name="message">Alert message</param>
 /// <param name="htmlAttributes">
 ///   [Optional] Any extras HTML attributes to be applied.
 ///   Note. These attributes are only applied to the top level div
 /// </param>
 /// <returns>A Bootstrap styled alert</returns>
 public static IExtendedHtmlString Alert(this HtmlHelper html, EMessage type, string message,
                                         object htmlAttributes = null)
 {
     return(Alert(html, type, message, string.Empty, null, htmlAttributes));
 }
示例#14
0
 internal void SetReply(EMessage reply)
 {
     ResponseMsg = reply;
     CountDown   = int.MaxValue;
     IsReplied   = true;
 }
 /// <summary>
 ///   Renders a Bootstrap alert
 /// </summary>
 /// <param name="html">HtmlHelper extension</param>
 /// <param name="type">Type of alert</param>
 /// <param name="message">Alert message</param>
 /// <param name="title">Title/Heading of the alert</param>
 /// <param name="htmlAttributes">
 ///   [Optional] Any extras HTML attributes to be applied.
 ///   Note. These attributes are only applied to the top level div
 /// </param>
 /// <returns>A Bootstrap styled alert</returns>
 public static IExtendedHtmlString Alert(this HtmlHelper html, EMessage type, string message, string title,
                                         object htmlAttributes = null)
 {
     return(Alert(html, type, message, title, (EBootstrapIcon?)null, htmlAttributes));
 }
 protected override void ProcessResponse(EMessage requestMsg, EMessage responseMsg)
 {
     // pass
 }
示例#17
0
 internal TCounter(EMessage msg, int timeout)
 {
     RequestMsg = msg;
     CountDown  = timeout;
     IsReplied  = false;
 }
        protected override void ProcessRequest(ref EMessage msg)
        {
            if (server.BlockMessage != null)
            {
                msg = new EMError(msg, server.BlockMessage, ErrorCode.ServerBlocked);
            }
            else if (msg.HasFlag(StatusCode.Login))
            {
                var  login = msg as EMLogin;
                bool hasLoggedIn;

                hasLoggedIn = server.MailCenter.IsOnline(login.Username);

                if (hasLoggedIn)
                {
                    server.PushOut(login.Username, $"You have been signed out because your account is logged in elsewhere.");
                }

                if (server.MailCenter.Contains(login.Username))
                {
                    var user = server.MailCenter.GetUser(login.Username, login.Password);

                    if (user != null)
                    {
                        TeleClientName = login.Username;
                        this.logger.SetOwner(TeleClientName);  // reset owner of logger
                        User        = user;
                        Token       = server.GenToken(TeleClientName);
                        msg         = new EMLoggedin(login, ClientName, user, Token);
                        msg.Status |= StatusCode.Duplex;  // sync time command
                        logger.SetOwner(TeleClientName);

                        Phase = ConnectionPhase.P2LoggedIn;
                        user.PostOffice.Activate(this);  // activate mailbox
                        user.IsOnline = true;

                        (msg as EMLoggedin).ServerTime = server.Now;  // set sync time
                    }
                    else
                    {
                        msg = new EMError(msg, $"incorrect username/password.", ErrorCode.IncorrectUsernameOrPassword);
                    }
                }
                else
                {
                    msg = new EMError(msg, $"user '{login.Username}' is not registered.", ErrorCode.UnregisteredUser);
                }
            }
            else if (User == null || !User.IsOnline)
            {
                msg = new EMError(msg, "please login first.");
            }
            else if (msg.HasFlag(StatusCode.Logout))
            {
                Logout();

                msg = new EMessage(msg, StatusCode.Ok);
            }
            else if (msg.HasFlag(StatusCode.Letter))
            {
                var letter = msg as EMLetter;

                try
                {
                    var result = server.MailCenter.Deliver(letter);
                    if (result == null)
                    {
                        msg = new EMessage(msg, StatusCode.Ok);  // Post, or SafePost
                    }
                    else
                    {
                        result.SetEnvelope(new Envelope(msg.ID));
                        msg = result;
                    }
                }
                catch (Exception ex)
                {
                    msg = new EMError(msg, ex.Message);
                }
            }
            else if (msg.HasFlag(StatusCode.Register))
            {
                if (msg.HasFlag(StatusCode.Entity))
                {
                    var entityNames = (msg as EMText).Text.Split(',');

                    foreach (var name in entityNames)
                    {
                        User.PostOffice.Register(name);
                    }

                    msg = new EMessage(msg, StatusCode.Ok);
                }
            }
            else
            {
                msg = new EMError(msg, $"current request is not supported by this server.", ErrorCode.InvalidOperation);
            }
        }
示例#19
0
 public void RegisterMessage(EMessage message, Action <GameSession, EMessage, Stream> handler)
 {
     _server.RegisterMessage(message, handler);
 }
示例#20
0
 /// <summary>
 ///   Constructor
 /// </summary>
 /// <param name="type">Type of alert</param>
 /// <param name="message">Alert message</param>
 /// <param name="title">Title/Heading of the alert</param>
 /// <param name="htmlAttributes">
 ///   [Optional] Any extras HTML attributes to be applied.
 ///   Note. These attributes are only applied to the top level div
 /// </param>
 public Alert(EMessage type, string message, string title, object htmlAttributes = null)
     : this(type, message, title, (EFontAwesomeIcon?)null, htmlAttributes)
 {
 }
 /// <summary>
 /// append 'msg' to the delivery queue
 /// </summary>
 /// <param name="msg"></param>
 protected void SendMessage(EMessage msg)
 {
     ThreadPool.QueueUserWorkItem(_processOutMessage, msg);  // create a task
 }
 internal void Write(LogType type, EMessage msg)
 {
     ThreadPool.QueueUserWorkItem(o => Write(type, msg.ToString()));
 }
 /// <summary>
 /// process the response message came from the remote agent
 /// </summary>
 /// <param name="requestMsg"></param>
 /// <param name="responseMsg"></param>
 protected abstract void ProcessResponse(EMessage requestMsg, EMessage responseMsg);
示例#24
0
		public virtual void SendMessage(EMessage message, EventArgs e) {
			MessageProcess(message, e);
		}
 /// <summary>
 /// this method will be invoked when the new arrived message is dequeued from in message queue
 /// </summary>
 /// <param name="msg"></param>
 protected virtual void PreprocessInMessage(ref EMessage msg)
 {
     // pass
 }
示例#26
0
		protected virtual void MessageProcess(EMessage message, EventArgs e) {
			switch (message) {
				case EMessage.Click: {
						ClickProcess(e as MouseEventArgs);
						break;
					}
				case EMessage.MouseDown: {
						MouseDownProcess(e as MouseEventArgs);
						break;
					}
				case EMessage.MouseUp: {
						MouseUpProcess(e as MouseEventArgs);
						break;
					}
				case EMessage.MousePress: {
						MousePressProcess(e as MouseEventArgs);
						break;
					}
				case EMessage.MouseMove: {
						MouseMoveProcess(e as MouseEventArgs);
						break;
					}
				case EMessage.MouseOver: {
						MouseOverProcess(e as MouseEventArgs);
						break;
					}
				case EMessage.MouseOut: {
						MouseOutProcess(e as MouseEventArgs);
						break;
					}
				case EMessage.GamePadDown: {
						GamePadDownProcess(e as GamePadEventArgs);
						break;
					}
				case EMessage.GamePadUp: {
						GamePadUpProcess(e as GamePadEventArgs);
						break;
					}
				case EMessage.GamePadPress: {
						GamePadPressProcess(e as GamePadEventArgs);
						break;
					}
				case EMessage.KeyDown: {
						KeyDownProcess(e as KeyEventArgs);
						break;
					}
				case EMessage.KeyUp: {
						KeyUpProcess(e as KeyEventArgs);
						break;
					}
				case EMessage.KeyPress: {
						KeyPressProcess(e as KeyEventArgs);
						break;
					}
			}
		}
        /// <summary>
        /// receive date stream through socket
        /// </summary>
        /// <param name="control"></param>
        private void __threadListen(ThreadControl control)
        {
            logger.Debug($"{nameof(__threadListen)}() on duty.");

            var  count = 1;                         // the actual received count of bytes by socket
            var  lenBuff = new byte[sizeof(uint)];  // store the message length number in byte format
            var  slot = new byte[slotSize];         // reception slot, it could maintain the integral data of a message
            int  k = 0, l = 0;                      // pointer for slot, pointer for lenBuff
            uint msgLen = 0, verifyLen = 0;         // message header, check code
            var  rbuffer    = new byte[bufferSize]; // reception buffer
            var  slotBackup = slot;                 // switch back to the primal slot after using super slot

            socket.SendBufferSize = this.bufferSize;

            while (!control.SafelyTerminating)
            {
                /*******************************
                * receive bytes through socket
                * *****************************/
                rwlsSocket.EnterReadLock();
                try
                {
                    var result = socket.BeginReceive(rbuffer, 0, rbuffer.Length, SocketFlags.None, x => x = null, null); // async reception,to realize 'SafelyTermination'
                    while (!control.SafelyTerminating && !result.IsCompleted)                                            // wait for completion
                    {
                        Thread.Sleep(1);
                    }
                    if (control.SafelyTerminating || !socket.Connected)
                    {
                        break;                                                  // termination signal detected, stop listening
                    }
                    count = socket.EndReceive(result);
                }
                catch (SocketException se)
                {
                    logger.Error($"{se.Message}");
                    break;
                }
                catch (Exception ex)
                {
                    logger.Fatal("fatal error occurred in __threadListen.", ex);
                    Catch(new EOCException(ex));
                    break;
                }
                finally
                {
                    rwlsSocket.ExitReadLock();
                }

                /*****************************
                * process the received bytes
                * ***************************/
                for (var j = 0; j < count;)  // deal with the bytes received in rbuffer
                {
                    if (msgLen == 0)
                    {
                        lenBuff[l] = rbuffer[j];
                        ++j;  // point to the 1st byte of content
                        if (++l == lenBuff.Length)
                        {
                            l      = 0;
                            msgLen = BitConverter.ToUInt32(lenBuff, 0);
                            if (verifyLen != 0)                       // need validation
                            {
                                if (verifyLen == msgLen)              // validatin OK
                                {
                                    watchDog = 0;                     // feed local dog, reset the timer
                                    if (msgLen == 1)                  // system command code
                                    {
                                        if (slot[0] == DOG_FOOD_FLAG) // dog food
                                        {
                                            // pass
                                        }
                                    }
                                    else
                                    {
                                        var msg = EMessage.FromBytes(slot, 0, k);
                                        ThreadPool.QueueUserWorkItem(_processInMessage, msg);
                                    }
                                    msgLen = 0;
                                }
                                else
                                {
                                    Catch(new EOCException("transmission error, please reconnect!"));
                                }
                                verifyLen = 0;
                                if (slot.Length != slotSize)
                                {
                                    slot = slotBackup;
                                }
                            }
                            else
                            {
                                if (msgLen > slotSize)
                                {
                                    slot = new byte[msgLen];  // super slot
                                }
                            }
                            k = 0;
                        }
                    }
                    else
                    {
                        int n = (int)(msgLen - k);
                        if (n + j > count)
                        {
                            n = count - j;
                        }
                        Array.Copy(rbuffer, j, slot, k, n);
                        k += n;
                        j += n;
                        if (k == msgLen)
                        {
                            verifyLen = msgLen;
                            msgLen    = 0;
                        }
                    }
                }
            }

            control.SetAbortedFlags();

            OnThreadListenAborted();

            logger.Debug($"{nameof(__threadListen)}() aborted.");
        }
示例#28
0
 private void OnS2C_MATCH(EMessage msg, Stream buff)
 {
 }
 /// <summary>
 /// Renders a jQuery UI alert
 /// </summary>
 /// <param name="html">HtmlHelper extension</param>
 /// <param name="type">Type of alert</param>
 /// <param name="message">Alert message</param>
 /// <param name="title">Title/Heading of the alert</param>
 /// <param name="htmlAttributes">[Optional] Any extras HTML attributes to be applied.
 /// Note. These attributes are only applied to the top level div</param>
 /// <returns>A jQuery UI styled alert</returns>
 public static Alert Alert(this HtmlHelper html, EMessage type, string message, string title, object htmlAttributes = null)
 {
     return(Alert(html, type, message, title, (EJQueryUIIcon?)null, htmlAttributes));
 }
示例#30
0
 private void OnS2C_MATCH_ALL_READY(EMessage msg, Stream buff)
 {
 }
示例#31
0
 public virtual object SendMessage(EMessage type) => null;
示例#32
0
 private void OnS2C_MATCH_SUCCESS(EMessage msg, Stream buff)
 {
 }
 /// <summary>
 ///   Renders a Bootstrap alert
 /// </summary>
 /// <param name="html">HtmlHelper extension</param>
 /// <param name="type">Type of alert</param>
 /// <param name="message">Alert message</param>
 /// <param name="title">Title/Heading of the alert</param>
 /// <param name="icon">Icon to be rendered with title/heading</param>
 /// <param name="htmlAttributes">
 ///   [Optional] Any extras HTML attributes to be applied.
 ///   Note. These attributes are only applied to the top level div
 /// </param>
 /// <returns>A Bootstrap styled alert</returns>
 public static IExtendedHtmlString Alert(this HtmlHelper html, EMessage type, string message, string title, EFontAwesomeIcon?icon,
                                         object htmlAttributes = null)
 {
     return(new ExtendedHtmlString(new Alert(type, message, title, icon, htmlAttributes)));
 }
示例#34
0
 public void resetProperties()
 {
     TestVar = -1;
     Message = EMessage.Invalid;
     this.Variables.Clear(false);
 }