예제 #1
0
        private void StartReceivingMessages()
        {
            _cancellation = new CancellationTokenSource();
            Task.Run(() =>
            {
                while (!_cancellation.IsCancellationRequested)
                {
                    try
                    {
                        var topic         = _socket.ReceiveFrameString();
                        var messageString = _socket.ReceiveFrameString();

                        var message = Message.Parse(messageString);

                        foreach (var @delegate in MessageReceived?.GetInvocationList().ToArray() ?? new Delegate[0])
                        {
                            ((Action <Message>)@delegate)?.BeginInvoke(message, null, null); // Do not wait while message will be handled
                        }
                    }
                    catch (Exception ex) when(ex is ObjectDisposedException || ex is SocketException)
                    {
                        // Ignore this one: _socket may be closed while waiting the message and this is fine
                    }
                    catch (Exception ex)
                    {
                        // TODO: Log Exception
                        Console.WriteLine("Error while receiving the message: " + ex);
                    }
                }
            }, _cancellation.Token);
        }
        public OSDMap FireMessageReceived(string SessionID, OSDMap message)
        {
            OSDMap result = null;
            ulong  reg;

            if (ulong.TryParse(SessionID, out reg)) //Local region
            {
                if (OnMessageReceived != null)
                {
                    MessageReceived eventCopy = OnMessageReceived;
                    foreach (OSDMap r in from MessageReceived messagedelegate in eventCopy.GetInvocationList() select messagedelegate(message) into r where r != null select r)
                    {
                        result = r;
                    }
                }
            }
            else //IWC
            {
                string[] session = SessionID.Split('|');
                ISyncMessagePosterService smps = m_registry.RequestModuleInterface <ISyncMessagePosterService>();
                //Forward it on
                result = smps.Get(message, UUID.Parse(session[0]), ulong.Parse(session[1]));
            }

            return(result);
        }
        private void Dispose(bool disposeManaged)
        {
            if (disposed)
            {
                return;
            }

            lock (disposeLock)
            {
                if (disposed)
                {
                    return;
                }

                disposed = true;
                subscriptionService.Dispose();
                if (!disposeManaged || MessageReceived == null)
                {
                    return;
                }

                var del = MessageReceived.GetInvocationList();
                foreach (var item in del)
                {
                    var msg = (Listeners.XDMessageHandler)item;
                    MessageReceived -= msg;
                }
            }
        }
예제 #4
0
        /// <summary>
        ///     Dispose implementation which ensures the native window is destroyed, and
        ///     managed resources detached.
        /// </summary>
        private void Dispose(bool disposeManaged)
        {
            if (!disposed)
            {
                lock (disposeLock)
                {
                    if (!disposed)
                    {
                        disposed = true;
                        if (disposeManaged)
                        {
                            if (MessageReceived != null)
                            {
                                // remove all handlers
                                Delegate[] del = MessageReceived.GetInvocationList();

                                foreach (MessageHandler msg in del)
                                {
                                    MessageReceived -= msg;
                                }
                            }
                            if (Handle != IntPtr.Zero)
                            {
                                DestroyHandle();
                                Dispose();
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Dispose implementation which ensures the native window is destroyed, and
        /// managed resources detached.
        /// </summary>
        private void Dispose(bool disposeManaged)
        {
            if (!disposed)
            {
                disposed = true;
                if (disposeManaged)
                {
                    if (networkRelay != null)
                    {
                        networkRelay.Dispose();
                        networkRelay = null;
                    }

                    if (MessageReceived != null)
                    {
                        // remove all handlers
                        Delegate[] del = MessageReceived.GetInvocationList();
                        foreach (XDMessageHandler msg in del)
                        {
                            MessageReceived -= msg;
                        }
                    }
                    if (this.Handle != IntPtr.Zero)
                    {
                        this.DestroyHandle();
                        this.Dispose();
                    }
                }
            }
        }
예제 #6
0
 /// <summary>
 ///     Dispose implementation which ensures the native window is destroyed, and
 ///     managed resources detached.
 /// </summary>
 private void Dispose(bool disposeManaged)
 {
     if (!disposed)
     {
         lock (disposeLock)
         {
             if (!disposed)
             {
                 disposed = true;
                 subscriptionService.Dispose();
                 if (disposeManaged)
                 {
                     if (MessageReceived != null)
                     {
                         // remove all handlers
                         var del = MessageReceived.GetInvocationList();
                         foreach (Listeners.XDMessageHandler msg in del)
                         {
                             MessageReceived -= msg;
                         }
                     }
                 }
             }
         }
     }
 }
예제 #7
0
 /// <summary>
 /// Broadcast message to all clients
 /// </summary>
 /// <param name="message">message string</param>
 public void Send(string message)
 {
     if (MessageReceived != null)
     {
         MessageHandler messageDelegate = null;
         Delegate[]     invocationList_ = null;
         try
         {
             invocationList_ = MessageReceived.GetInvocationList();
         }
         catch (MemberAccessException ex)
         {
             throw ex;
         }
         if (invocationList_ != null)
         {
             lock (this)
             {
                 foreach (Delegate del in invocationList_)
                 {
                     messageDelegate = (MessageHandler)del;
                     WrapperDelegate wrDel    = new WrapperDelegate(BeginSend);
                     AsyncCallback   callback = new AsyncCallback(EndSend);
                     wrDel.BeginInvoke(message, messageDelegate, callback, wrDel);
                 }
             }
         }
     }
 }
예제 #8
0
 public void UnsubscribeAllHandlers()
 {
     if (MessageReceived != null)
     {
         foreach (var handler in MessageReceived.GetInvocationList())
         {
             MessageReceived -= handler as Action <CombatLogType, string>;
         }
     }
 }
예제 #9
0
 private void FireRecieveEvent(Message msg)
 {
     if (MessageReceived != null)
     {
         var receivers = MessageReceived.GetInvocationList();
         foreach (MessageDelegates.MessageReceivedEventHandler receiver in receivers)
         {
             receiver.BeginInvoke(this, new MessageEventArgs(msg), null, null);
         }
     }
 }
예제 #10
0
 public void Dispose()
 {
     _locker?.Dispose();
     if (MessageReceived != null)
     {
         foreach (var d in MessageReceived.GetInvocationList())
         {
             MessageReceived -= (d as MessageReceived <StreamItemCollection>);
         }
     }
 }
예제 #11
0
        private async Task dispatchReceiveHandler(Message message)
        {
            if (MessageReceived == null)
            {
                return;
            }

            foreach (var handler in MessageReceived.GetInvocationList())
            {
                await((IrcClientMessageEventHandler)handler)(this, message);
            }
        }
        /// <summary>
        /// Dispose implementation, which ensures the native window is destroyed
        /// </summary>
        private void Dispose(bool disposeManaged)
        {
            if (!disposed)
            {
                disposed = true;
                if (disposeManaged)
                {
                    if (MessageReceived != null)
                    {
                        // remove all handlers
                        Delegate[] del = MessageReceived.GetInvocationList();
                        foreach (TheCodeKing.Net.Messaging.XDListener.XDMessageHandler msg in del)
                        {
                            MessageReceived -= msg;
                        }
                    }
                    if (activeThreads != null)
                    {
                        // grab a reference to the current list of threads
                        var values = new List <MailSlotThreadInfo>(activeThreads.Values);

                        // removing the channels, will cause threads to terminate
                        activeThreads.Clear();
                        // shut down listener threads
                        foreach (MailSlotThreadInfo info in values)
                        {
                            // close any read handles
                            if (info.HasValidFileHandle)
                            {
                                Native.CloseHandle(info.FileHandle);
                            }

                            // ensure threads shut down
                            if (info.Thread.IsAlive)
                            {
                                // interrupt incase of asleep thread
                                info.Thread.Interrupt();
                            }
                            // try to join thread
                            if (info.Thread.IsAlive)
                            {
                                if (!info.Thread.Join(500))
                                {
                                    // last resort abort thread
                                    //info.Thread.Abort(); Do Nothing
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #13
0
        public void OnMessageReceived(Message message)
        {
            if (MessageReceived == null)
            {
                return;
            }

            var delegates = MessageReceived.GetInvocationList();

            Parallel.ForEach(delegates, d => d.DynamicInvoke(this, message));

            // MessageReceived.Invoke(this, message);
        }
예제 #14
0
 private static bool _Invoke(object sender, MessageType type, object data)
 {
     foreach (var subscriber in MessageReceived.GetInvocationList())
     {
         try {
             subscriber.DynamicInvoke(sender, type, data);
         }
         catch {
             return(false);
         }
     }
     return(true);
 }
예제 #15
0
 private void CallMessageReceived(RsaKeyParameters senderKey, bool isPublic, T message, byte[] payload)
 {
     if (MessageReceived != null)
     {
         foreach (var d in MessageReceived.GetInvocationList())
         {
             try
             {
                 (d as MessageReceivedEventHandler)(this, senderKey, isPublic, message, payload);
             }
             catch { }
         }
     }
 }
예제 #16
0
        public OSDMap FireMessageReceived(string SessionID, OSDMap message)
        {
            OSDMap result = null;

            if (OnMessageReceived != null)
            {
                MessageReceived eventCopy = OnMessageReceived;
                foreach (OSDMap r in from MessageReceived messagedelegate in eventCopy.GetInvocationList() select messagedelegate(message) into r where r != null select r)
                {
                    result = r;
                }
            }
            return(result);
        }
예제 #17
0
 private void MessengerOnMessageReceived(string from, string message)
 {
     Logger.LogNotice($"SIP message received from '{from}': {message}");
     foreach (var handler in MessageReceived?.GetInvocationList() ?? Enumerable.Empty <Delegate>())
     {
         try
         {
             handler.DynamicInvoke(from, message);
         }
         catch (Exception e)
         {
             Logger.LogWarn(e, "Exception occured while processing 'MessageReceived' event");
         }
     }
 }
예제 #18
0
        private void Dispose(bool disposeManaged)
        {
            if (disposed)
            {
                return;
            }

            lock (disposeLock)
            {
                if (disposed)
                {
                    return;
                }

                disposed = true;
                if (!disposeManaged)
                {
                    return;
                }

                if (MessageReceived != null)
                {
                    var del = MessageReceived.GetInvocationList();
                    foreach (var item in del)
                    {
                        var msg = (Listeners.XDMessageHandler)item;
                        MessageReceived -= msg;
                    }
                }
                if (watcherList == null)
                {
                    return;
                }

                foreach (var watcher in watcherList.Values)
                {
                    watcher.EnableRaisingEvents = false;
                    watcher.Changed            -= OnMessageReceived;
                    watcher.Dispose();
                }

                watcherList.Clear();
                watcherList = null;
            }
        }
예제 #19
0
파일: Chat.cs 프로젝트: Arcidev/Card-Game
        public void UnsubscribeAllHandlers()
        {
            if (ErrorOccured != null)
            {
                foreach (var handler in ErrorOccured.GetInvocationList())
                {
                    ErrorOccured -= handler as Action <ChatType, string, string>;
                }
            }

            if (MessageReceived != null)
            {
                foreach (var handler in MessageReceived.GetInvocationList())
                {
                    MessageReceived -= handler as Action <ChatType, string, string>;
                }
            }
        }
예제 #20
0
        private void Dispose(bool disposeManaged)
        {
            if (disposed)
            {
                return;
            }

            lock (disposeLock)
            {
                if (disposed)
                {
                    return;
                }

                disposed = true;
                if (!disposeManaged)
                {
                    return;
                }

                if (MessageReceived != null)
                {
                    var del = MessageReceived.GetInvocationList();
                    foreach (var item in del)
                    {
                        var msg = (Listeners.XDMessageHandler)item;
                        MessageReceived -= msg;
                    }
                }
                if (Handle == IntPtr.Zero)
                {
                    return;
                }

                DestroyHandle();
                Dispose();
            }
        }
예제 #21
0
        private void Update()
        {
            lock (lockObj)
            {
                while (m_incomingMessageQueue.Count > 0)
                {
                    NetInMessage receivedMessage = m_incomingMessageQueue.Dequeue();
                    if (MessageReceived != null)
                    {
                        Delegate[] invocationList = MessageReceived.GetInvocationList();
                        if (invocationList != null)
                        {
                            for (int i = 0; i < invocationList.Length; i++)
                            {
                                receivedMessage.ResetIndex();

                                invocationList[i].DynamicInvoke(receivedMessage);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Dispose implementation, which ensures the native window is destroyed
        /// </summary>
        private void Dispose(bool disposeManaged)
        {
            if (!disposed)
            {
                disposed = true;
                if (disposeManaged)
                {
                    if (networkRelay != null)
                    {
                        networkRelay.Dispose();
                        networkRelay = null;
                    }

                    if (MessageReceived != null)
                    {
                        // remove all handlers
                        Delegate[] del = MessageReceived.GetInvocationList();
                        foreach (TheCodeKing.Net.Messaging.XDListener.XDMessageHandler msg in del)
                        {
                            MessageReceived -= msg;
                        }
                    }
                    if (watcherList != null)
                    {
                        // shut down watchers
                        foreach (FileSystemWatcher watcher in watcherList.Values)
                        {
                            watcher.EnableRaisingEvents = false;
                            watcher.Changed            -= new FileSystemEventHandler(OnMessageReceived);
                            watcher.Dispose();
                        }
                        watcherList.Clear();
                        watcherList = null;
                    }
                }
            }
        }
예제 #23
0
 /// <summary>
 ///     Dispose implementation, which ensures the native window is destroyed
 /// </summary>
 private void Dispose(bool disposeManaged)
 {
     if (!disposed)
     {
         lock (disposeLock)
         {
             if (!disposed)
             {
                 disposed = true;
                 if (disposeManaged)
                 {
                     if (MessageReceived != null)
                     {
                         // remove all handlers
                         Delegate[] del = MessageReceived.GetInvocationList();
                         foreach (Listeners.XDMessageHandler msg in del)
                         {
                             MessageReceived -= msg;
                         }
                     }
                     if (watcherList != null)
                     {
                         // shut down watchers
                         foreach (var watcher in watcherList.Values)
                         {
                             watcher.EnableRaisingEvents = false;
                             watcher.Changed            -= OnMessageReceived;
                             watcher.Dispose();
                         }
                         watcherList.Clear();
                         watcherList = null;
                     }
                 }
             }
         }
     }
 }
예제 #24
0
        public void Update()
        {
            if (networkClient.ReadMessages(_receivedMessages) > 0)
            {
                try
                {
                    if (_receivedMessages.Any(x => x.PeekByte() != (byte)CommandType.UpdateVoIPData))
                    {
                        float packetTime = (float)DateTime.UtcNow.Subtract(_lastPacketTime).TotalMilliseconds;
                        if (packetTime > 2f)
                        {
                            _averagePacketTimes.Add(packetTime);

                            if (_averagePacketTimes.Count > 150)
                            {
                                _averagePacketTimes.RemoveAt(0);
                            }

                            tickrate = (float)Math.Round(1000f / _averagePacketTimes.Where(x => x > 2f).Average(), 2);
                        }
                        _lastPacketTime = DateTime.UtcNow;
                    }

                    try
                    {
                        if (Config.Instance.SpectatorMode)
                        {
                            foreach (var lastPlayerHistoryUpdates in _receivedMessages.Where(x => x.MessageType == NetIncomingMessageType.Data && x.PeekByte() == (byte)CommandType.GetPlayerUpdates))
                            {
                                foreach (Action <NetIncomingMessage> nextDel in PlayerInfoUpdateReceived.GetInvocationList())
                                {
                                    try
                                    {
                                        lastPlayerHistoryUpdates.Position = 0;
                                        nextDel?.Invoke(lastPlayerHistoryUpdates);
                                    }
                                    catch (Exception e)
                                    {
                                        if (nextDel != null)
                                        {
                                            Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on update received event: {e}");
                                        }
                                        else
                                        {
                                            Plugin.log.Error($"Exception on update received event: {e}");
                                        }
                                    }
                                }
                                lastPlayerHistoryUpdates.Position = 0;
                            }
                        }
                    }catch (Exception e)
                    {
                        Plugin.log.Error("Unable to parse GetPlayerUpdates message! Exception: " + e);
                    }

                    try
                    {
                        NetIncomingMessage lastUpdate = _receivedMessages.LastOrDefault(x => x.MessageType == NetIncomingMessageType.Data && x.PeekByte() == (byte)CommandType.UpdatePlayerInfo);

                        if (lastUpdate != null)
                        {
                            _receivedMessages.RemoveAll(x => x.MessageType == NetIncomingMessageType.Data && x.PeekByte() == (byte)CommandType.UpdatePlayerInfo);

                            foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                            {
                                try
                                {
                                    lastUpdate.Position = 0;
                                    nextDel?.Invoke(lastUpdate);
                                }
                                catch (Exception e)
                                {
                                    if (nextDel != null)
                                    {
                                        Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on update received event: {e}");
                                    }
                                    else
                                    {
                                        Plugin.log.Error($"Exception on update received event: {e}");
                                    }
                                }
                            }
                            lastUpdate.Position = 0;
                        }
                    }catch (Exception e)
                    {
                        Plugin.log.Error("Unable to parse UpdatePlayerInfo message! Exception: " + e);
                    }

                    foreach (NetIncomingMessage msg in _receivedMessages)
                    {
                        switch (msg.MessageType)
                        {
                        case NetIncomingMessageType.StatusChanged:
                        {
                            NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();

                            if (status == NetConnectionStatus.Connected && !connected)
                            {
                                connected = true;
                                ConnectedToServerHub?.Invoke();
                            }
                            else if (status == NetConnectionStatus.Disconnected && connected)
                            {
#if DEBUG
                                Plugin.log.Info("Disconnecting...");
#endif
                                Disconnect();

                                foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                                {
                                    try
                                    {
                                        nextDel?.Invoke(null);
                                    }
                                    catch (Exception e)
                                    {
                                        if (nextDel != null)
                                        {
                                            Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on message received event: {e}");
                                        }
                                        else
                                        {
                                            Plugin.log.Error($"Exception on message received event: {e}");
                                        }
                                    }
                                }
                            }
                            else if (status == NetConnectionStatus.Disconnected && !connected)
                            {
                                Plugin.log.Error("ServerHub refused connection! Reason: " + msg.ReadString());
                            }
                        }
                        break;

                        case NetIncomingMessageType.Data:
                        {
                            CommandType commandType = (CommandType)msg.PeekByte();

                            if (commandType == CommandType.Disconnect)
                            {
#if DEBUG
                                Plugin.log.Info("Disconnecting...");
#endif
                                Disconnect();

                                foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                                {
                                    try
                                    {
                                        msg.Position = 0;
                                        nextDel?.Invoke(msg);
                                    }
                                    catch (Exception e)
                                    {
                                        if (nextDel != null)
                                        {
                                            Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on message received event: {e}");
                                        }
                                        else
                                        {
                                            Plugin.log.Error($"Exception on message received event: {e}");
                                        }
                                    }
                                }

                                return;
                            }
                            else if (commandType == CommandType.SendEventMessage)
                            {
                                string header = msg.ReadString();
                                string data   = msg.ReadString();

#if DEBUG
                                Plugin.log.Info($"Received event message! Header=\"{header}\", Data=\"{data}\"");
#endif
                                foreach (Action <string, string> nextDel in EventMessageReceived.GetInvocationList())
                                {
                                    try
                                    {
                                        nextDel?.Invoke(header, data);
                                    }
                                    catch (Exception e)
                                    {
                                        if (nextDel != null)
                                        {
                                            Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on event message received event: {e}");
                                        }
                                        else
                                        {
                                            Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on event message received event: {e}");
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (MessageReceived != null)
                                {
                                    foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                                    {
                                        try
                                        {
                                            msg.Position = 0;
                                            nextDel?.Invoke(msg);
                                        }
                                        catch (Exception e)
                                        {
                                            if (nextDel != null)
                                            {
                                                Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on message received event: {e}");
                                            }
                                            else
                                            {
                                                Plugin.log.Error($"Exception on message received event: {e}");
                                            }
                                        }
                                    }
                                }
                            }


                            if (commandType == CommandType.JoinRoom)
                            {
                                msg.Position = 8;
                                if (msg.PeekByte() == 0 && ClientJoinedRoom != null)
                                {
                                    foreach (Action nextDel in ClientJoinedRoom.GetInvocationList())
                                    {
                                        try
                                        {
                                            nextDel?.Invoke();
                                        }
                                        catch (Exception e)
                                        {
                                            if (nextDel != null)
                                            {
                                                Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on client joined room event: {e}");
                                            }
                                            else
                                            {
                                                Plugin.log.Error($"Exception on client joined room event: {e}");
                                            }
                                        }
                                    }
                                }
                            }
                            else if (commandType == CommandType.StartLevel)
                            {
#if DEBUG
                                startNewDump = true;
                                packetsBuffer.Clear();
                                msg.Position = 8;
                                LevelOptionsInfo levelInfo = new LevelOptionsInfo(msg);
                                SongInfo         songInfo  = new SongInfo(msg);
                                List <byte>      buffer    = new List <byte>();
                                buffer.AddRange(levelInfo.ToBytes());
                                buffer.AddRange(HexConverter.ConvertHexToBytesX(songInfo.levelId));

                                Plugin.log.Info("LevelID: " + songInfo.levelId + ", Bytes: " + BitConverter.ToString(buffer.ToArray()));

                                packetsBuffer.Enqueue(buffer.ToArray());
                                msg.Position = 0;
#endif
                                if (playerInfo.playerState == PlayerState.Room)
                                {
                                    foreach (Action nextDel in ClientLevelStarted.GetInvocationList())
                                    {
                                        try
                                        {
                                            nextDel?.Invoke();
                                        }
                                        catch (Exception e)
                                        {
                                            if (nextDel != null)
                                            {
                                                Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on client level started event: {e}");
                                            }
                                            else
                                            {
                                                Plugin.log.Error($"Exception on client level started event: {e}");
                                            }
                                        }
                                    }
                                }
                            }
                        };
                            break;

                        case NetIncomingMessageType.WarningMessage:
                            Plugin.log.Warn(msg.ReadString());
                            break;

                        case NetIncomingMessageType.ErrorMessage:
                            Plugin.log.Error(msg.ReadString());
                            break;

#if DEBUG
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.DebugMessage:
                            Plugin.log.Info(msg.ReadString());
                            break;

                        default:
                            Plugin.log.Info("Unhandled message type: " + msg.MessageType);
                            break;
#endif
                        }
                        networkClient.Recycle(msg);
                    }
                }catch (Exception e)
                {
#if DEBUG
                    Plugin.log.Critical($"Exception on message received event: {e}");
#endif
                }
                _receivedMessages.Clear();
            }

            if (connected && networkClient.ConnectionsCount == 0)
            {
#if DEBUG
                Plugin.log.Info("Connection lost! Disconnecting...");
#endif
                Disconnect();

                foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                {
                    try
                    {
                        nextDel.Invoke(null);
                    }
                    catch (Exception e)
                    {
                        if (nextDel != null)
                        {
                            Plugin.log.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on message received event: {e}");
                        }
                        else
                        {
                            Plugin.log.Error($"Exception on message received event: {e}");
                        }
                    }
                }
            }
        }
예제 #25
0
        public void Update()
        {
            NetIncomingMessage msg;

            while ((msg = NetworkClient.ReadMessage()) != null)
            {
                float packetTime = (float)DateTime.UtcNow.Subtract(_lastPacketTime).TotalMilliseconds;
                if (packetTime > 3f)
                {
                    _averagePacketTimes.Add(packetTime);

                    if (_averagePacketTimes.Count > 300)
                    {
                        _averagePacketTimes.RemoveAt(0);
                    }

                    Tickrate = (float)Math.Round(1000f / _averagePacketTimes.Average(), 2);
                }
                _lastPacketTime = DateTime.UtcNow;
                switch (msg.MessageType)
                {
                case NetIncomingMessageType.StatusChanged:
                {
                    NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();

                    if (status == NetConnectionStatus.Connected && !Connected)
                    {
                        Connected = true;
                        ConnectedToServerHub?.Invoke();
                    }
                    else
                    {
                        Misc.Logger.Info("New connection state: " + status);
                    }
                }
                break;

                case NetIncomingMessageType.Data:
                {
                    CommandType commandType = (CommandType)msg.PeekByte();

                    if (commandType == CommandType.Disconnect)
                    {
#if DEBUG
                        Misc.Logger.Info("Disconnecting...");
#endif
                        Disconnect();

                        foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                        {
                            try
                            {
                                msg.Position = 0;
                                nextDel.Invoke(msg);
                            }
                            catch (Exception e)
                            {
                                Misc.Logger.Error($"Exception in {nextDel.Method.Name} on message received event: {e}");
                            }
                        }

                        return;
                    }
                    else if (commandType == CommandType.SendEventMessage)
                    {
                        string header = msg.ReadString();
                        string data   = msg.ReadString();

#if DEBUG
                        Misc.Logger.Info($"Received event message! Header=\"{header}\", Data=\"{data}\"");
#endif
                        EventMessageReceived?.Invoke(header, data);
                    }
                    else
                    {
                        foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                        {
                            try
                            {
                                msg.Position = 0;
                                nextDel.Invoke(msg);
                            }
                            catch (Exception e)
                            {
                                Misc.Logger.Error($"Exception in {nextDel.Method.Name} on message received event: {e}");
                            }
                        }
                    }


                    if (commandType == CommandType.JoinRoom)
                    {
                        msg.Position = 8;
                        if (msg.PeekByte() == 0)
                        {
                            ClientJoinedRoom?.Invoke();
                        }
                    }
                    else if (commandType == CommandType.StartLevel)
                    {
                        if (playerInfo.playerState == PlayerState.Room)
                        {
                            ClientLevelStarted?.Invoke();
                        }
                    }
                };
                    break;

                case NetIncomingMessageType.WarningMessage:
                    Misc.Logger.Warning(msg.ReadString());
                    break;

                case NetIncomingMessageType.ErrorMessage:
                    Misc.Logger.Error(msg.ReadString());
                    break;

#if DEBUG
                case NetIncomingMessageType.VerboseDebugMessage:
                case NetIncomingMessageType.DebugMessage:
                    Misc.Logger.Info(msg.ReadString());
                    break;

                default:
                    Misc.Logger.Info("Unhandled message type: " + msg.MessageType);
                    break;
#endif
                }
                NetworkClient.Recycle(msg);
            }
        }
예제 #26
0
        public void Update()
        {
            if (NetworkClient.ReadMessages(_receivedMessages) > 0)
            {
                try
                {
                    if (_receivedMessages.Any(x => x.PeekByte() != (byte)CommandType.UpdateVoIPData))
                    {
                        float packetTime = (float)DateTime.UtcNow.Subtract(_lastPacketTime).TotalMilliseconds;
                        if (packetTime > 2f)
                        {
                            _averagePacketTimes.Add(packetTime);

                            if (_averagePacketTimes.Count > 150)
                            {
                                _averagePacketTimes.RemoveAt(0);
                            }

                            Tickrate = (float)Math.Round(1000f / _averagePacketTimes.Where(x => x > 2f).Average(), 2);
                        }
                        _lastPacketTime = DateTime.UtcNow;
                    }

                    NetIncomingMessage lastUpdate = _receivedMessages.LastOrDefault(x => x.MessageType == NetIncomingMessageType.Data && x.PeekByte() == (byte)CommandType.UpdatePlayerInfo);

                    if (lastUpdate != null)
                    {
                        foreach (NetIncomingMessage msg in _receivedMessages.Where(x => x.MessageType == NetIncomingMessageType.Data && x.PeekByte() == (byte)CommandType.UpdatePlayerInfo))
                        {
                            foreach (Action <NetIncomingMessage> nextDel in PlayerInfoUpdateReceived.GetInvocationList())
                            {
                                try
                                {
                                    msg.Position = 0;
                                    nextDel.Invoke(msg);
                                }
                                catch (Exception e)
                                {
                                    Misc.Logger.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on update received event: {e}");
                                }
                            }
                        }

                        _receivedMessages.RemoveAll(x => x.MessageType == NetIncomingMessageType.Data && x.PeekByte() == (byte)CommandType.UpdatePlayerInfo);

                        foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                        {
                            try
                            {
                                lastUpdate.Position = 0;
                                nextDel.Invoke(lastUpdate);
                            }
                            catch (Exception e)
                            {
                                Misc.Logger.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on message received event: {e}");
                            }
                        }
                    }

                    foreach (NetIncomingMessage msg in _receivedMessages)
                    {
                        switch (msg.MessageType)
                        {
                        case NetIncomingMessageType.StatusChanged:
                        {
                            NetConnectionStatus status = (NetConnectionStatus)msg.ReadByte();

                            if (status == NetConnectionStatus.Connected && !Connected)
                            {
                                Connected = true;
                                ConnectedToServerHub?.Invoke();
                            }
                            else if (status == NetConnectionStatus.Disconnected && Connected)
                            {
#if DEBUG
                                Misc.Logger.Info("Disconnecting...");
#endif
                                Disconnect();

                                foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                                {
                                    try
                                    {
                                        nextDel.Invoke(null);
                                    }
                                    catch (Exception e)
                                    {
                                        Misc.Logger.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on message received event: {e}");
                                    }
                                }
                            }
                            else if (status == NetConnectionStatus.Disconnected && !Connected)
                            {
                                Misc.Logger.Info("ServerHub refused connection! Reason: " + msg.ReadString());
                            }
                        }
                        break;

                        case NetIncomingMessageType.Data:
                        {
                            CommandType commandType = (CommandType)msg.PeekByte();

                            if (commandType == CommandType.Disconnect)
                            {
#if DEBUG
                                Misc.Logger.Info("Disconnecting...");
#endif
                                Disconnect();

                                foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                                {
                                    try
                                    {
                                        msg.Position = 0;
                                        nextDel.Invoke(msg);
                                    }
                                    catch (Exception e)
                                    {
                                        Misc.Logger.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on message received event: {e}");
                                    }
                                }

                                return;
                            }
                            else if (commandType == CommandType.SendEventMessage)
                            {
                                string header = msg.ReadString();
                                string data   = msg.ReadString();

#if DEBUG
                                Misc.Logger.Info($"Received event message! Header=\"{header}\", Data=\"{data}\"");
#endif
                                foreach (Action <string, string> nextDel in EventMessageReceived.GetInvocationList())
                                {
                                    try
                                    {
                                        nextDel.Invoke(header, data);
                                    }
                                    catch (Exception e)
                                    {
                                        Misc.Logger.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on event message received event: {e}");
                                    }
                                }
                            }
                            else
                            {
                                if (MessageReceived != null)
                                {
                                    foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                                    {
                                        try
                                        {
                                            msg.Position = 0;
                                            nextDel.Invoke(msg);
                                        }
                                        catch (Exception e)
                                        {
                                            Misc.Logger.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on message received event: {e}");
                                        }
                                    }
                                }
                            }


                            if (commandType == CommandType.JoinRoom)
                            {
                                msg.Position = 8;
                                if (msg.PeekByte() == 0 && ClientJoinedRoom != null)
                                {
                                    foreach (Action nextDel in ClientJoinedRoom.GetInvocationList())
                                    {
                                        try
                                        {
                                            nextDel.Invoke();
                                        }
                                        catch (Exception e)
                                        {
                                            Misc.Logger.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on client joined room event: {e}");
                                        }
                                    }
                                }
                            }
                            else if (commandType == CommandType.StartLevel)
                            {
                                if (playerInfo.playerState == PlayerState.Room)
                                {
                                    foreach (Action nextDel in ClientLevelStarted.GetInvocationList())
                                    {
                                        try
                                        {
                                            nextDel.Invoke();
                                        }
                                        catch (Exception e)
                                        {
                                            Misc.Logger.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on client level started event: {e}");
                                        }
                                    }
                                }
                            }
                        };
                            break;

                        case NetIncomingMessageType.WarningMessage:
                            Misc.Logger.Warning(msg.ReadString());
                            break;

                        case NetIncomingMessageType.ErrorMessage:
                            Misc.Logger.Error(msg.ReadString());
                            break;

#if DEBUG
                        case NetIncomingMessageType.VerboseDebugMessage:
                        case NetIncomingMessageType.DebugMessage:
                            Misc.Logger.Info(msg.ReadString());
                            break;

                        default:
                            Misc.Logger.Info("Unhandled message type: " + msg.MessageType);
                            break;
#endif
                        }
                        NetworkClient.Recycle(msg);
                    }
                }catch (Exception e)
                {
#if DEBUG
                    Misc.Logger.Exception($"Exception on message received event: {e}");
#endif
                }
                _receivedMessages.Clear();
            }

            if (Connected && NetworkClient.ConnectionsCount == 0)
            {
#if DEBUG
                Misc.Logger.Info("Connection lost! Disconnecting...");
#endif
                Disconnect();

                foreach (Action <NetIncomingMessage> nextDel in MessageReceived.GetInvocationList())
                {
                    try
                    {
                        nextDel.Invoke(null);
                    }
                    catch (Exception e)
                    {
                        Misc.Logger.Error($"Exception in {nextDel.Target.GetType()}.{nextDel.Method.Name} on message received event: {e}");
                    }
                }
            }
        }