示例#1
0
        public async Task <ResponsePacket> Ping(long timeout)
        {
            var connected = false;

            if (!_isConnected(_client))
            {
                return(new ResponsePacket()
                {
                    Data = Result.Disconnected
                });
            }

            PacketEventHandler handler = (sender, e) =>
            {
                if (e.Message.Command == "pong")
                {
                    connected = true;
                }
            };

            this.PacketReceivedEvent += handler;
            await Send(new PingPacket());

            var timeoutWatch = Stopwatch.StartNew();

            SpinWait.SpinUntil(() => connected || timeoutWatch.ElapsedMilliseconds >= timeout);
            this.PacketReceivedEvent -= handler;
            return(!connected ? new ResponsePacket()
            {
                Data = Result.Disconnected
            } : new ResponsePacket()
            {
                Data = Result.Success
            });
        }
示例#2
0
 public void Add(PacketEventHandler handler, PacketHandlerPriority priority = PacketHandlerPriority.Normal)
 {
     lock (lckObj)
     {
         Remove(handler);
         var container = new PacketHandlerPriorityContainer(handler, priority);
         containersTable[handler] = container;
         handlersSet.Add(container);
     }
 }
示例#3
0
        public virtual void AddHandler(PacketIdentifier packetId, PacketEventHandler handler, int priority = 0)
        {
            SortedSet <PacketEventHandlerPriority> handlersList;

            if (!handlers.TryGetValue(packetId, out handlersList))
            {
                handlersList = new SortedSet <PacketEventHandlerPriority>();
                handlers.Add(packetId, handlersList);
            }
            handlersList.Add(new PacketEventHandlerPriority(handlerId++, priority, handler));
        }
示例#4
0
 protected void RaiseEvent <T>(PacketEventHandler <T> handler, SecurePacketBasedClient client, T packet)
 {
     if (handler != null)
     {
         handler(client, packet);
     }
     else
     {
         Console.WriteLine("Unhandled packet: " + packet.ToString());
     }
 }
示例#5
0
文件: ModuleBase.cs 项目: nikes/Link
        protected bool Register <TPacket>(PacketEventHandler handler, PacketHandlerPriority priority = PacketHandlerPriority.Normal) where TPacket : IDataSerializer
        {
            var info = Session.Proto.GetInfo <TPacket>();

            if (info == null)
            {
                return(false);
            }
            Register(info.Id, handler, priority);
            return(true);
        }
示例#6
0
 public void Remove(PacketEventHandler handler)
 {
     lock (lckObj)
     {
         PacketHandlerPriorityContainer container;
         if (containersTable.TryGetValue(handler, out container))
         {
             handlersSet.Remove(container);
         }
         containersTable.Remove(handler);
     }
 }
示例#7
0
        public virtual void AddHandler(uint packetId, PacketEventHandler handler, int priority = 0)
        {
            SortedSet <PacketHandlerContainer> handlersList;

            if (!handlers.TryGetValue(packetId, out handlersList))
            {
                handlersList = new SortedSet <PacketHandlerContainer>();
                handlers.Add(packetId, handlersList);
            }
            var container = new PacketHandlerContainer(handler, priority, ++id);

            handlersList.Add(container);
        }
示例#8
0
 void RaisePacketEvent(string tag, long msgno, byte[] data, int offset, int len)
 {
     if (closed)
     {
         return;                 // paranoia
     }
     evq.Enqueue(() => {
         PacketEventHandler handler = OnPacket;
         if (handler != null)
         {
             handler(tag, msgno, data, offset, len);
         }
     });
 }
示例#9
0
        /// <summary>
        /// Starts the network handler. (Connects to a minecraft server)
        /// </summary>
        public void Start()
        {
            try {
                _baseSock = new TcpClient();
                var ar = _baseSock.BeginConnect(_mainMc.ServerIp, _mainMc.ServerPort, null, null);

                using (var wh = ar.AsyncWaitHandle) {
                    if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
                    {
                        _baseSock.Close();
                        RaiseSocketError(this, "Failed to connect: Connection Timeout");
                        return;
                    }

                    _baseSock.EndConnect(ar);
                }
            } catch (Exception e) {
                RaiseSocketError(this, "Failed to connect: " + e.Message);
                return;
            }

            _mainMc.Running = true;

            RaiseSocketInfo(this, "Connected to server.");
            RaiseSocketDebug(this, string.Format("IP: {0} Port: {1}", _mainMc.ServerIp, _mainMc.ServerPort.ToString()));

            // -- Create our Wrapped socket.
            _baseStream = _baseSock.GetStream();
            WSock       = new Wrapped(_baseStream);
            RaiseSocketDebug(this, "Socket Created");

            DoHandshake();

            _packetHandlers = new PacketEventHandler(this);

            // -- Start network parsing.
            _handler = new Thread(NetworkPacketHandler);
            _handler.Start();
            RaiseSocketDebug(this, "Handler thread started");
        }
示例#10
0
 protected void OnNewPacket(Packet p)
 {
     PacketEventHandler?.Invoke(this, p);
 }
示例#11
0
 public virtual void AddHandler(uint packetId, PacketType packetType, PacketEventHandler handler, int priority = 0)
 {
     AddHandler(new PacketIdentifier(packetId, packetType), handler);
 }
示例#12
0
 public PacketHandlerContainer(PacketEventHandler handler, int priority, int id)
 {
     Handler  = handler;
     Priority = priority;
     Id       = id;
 }
示例#13
0
        /// <summary>
        /// Send the packet to every current messenger and add it to the packet cache if it's cachable
        /// </summary>
        /// <param name="envelope"></param>
        private void DispatchPacket(PacketEnvelope envelope)
        {
            IMessengerPacket packet;

            lock (envelope)
            {
                packet = envelope.Packet; // rather than dig it out each time
                bool writeThrough = envelope.WriteThrough;

                // Any special handling for this packet?
                if (envelope.IsCommand)
                {
                    //this is a command packet, we process it as a command instead of just a data message
                    CommandPacket commandPacket = (CommandPacket)packet;

                    // Is this our exit or shutdown packet?  We need to handle those here.
                    if (commandPacket.Command == MessagingCommand.ExitMode)
                    {
                        m_ExitMode = true; // Mark us in ExitMode.  We will be by the time this method returns.
                        // Make sure we block until each messenger flushes, even if we weren't already in writeThrough mode.
                        writeThrough = true;
                    }
                    else if (commandPacket.Command == MessagingCommand.CloseMessenger)
                    {
                        m_Shutdown = true; // Mark us as shut down.  We will be by the time this method returns.
                        // Make sure we block until each messenger closes, even if we weren't already in writeThrough mode.
                        writeThrough = true;
                    }
                }
                else
                {
                    // Not a command, so it must be a Gibraltar data packet of some type.

                    //stamp the packet, and all of its dependent packets (this sets the sequence number)
                    StampPacket(packet, packet.Timestamp);

                    GibraltarPacket gibraltarPacket = packet as GibraltarPacket;
                    if (gibraltarPacket != null)
                    {
                        //this is a gibraltar packet so lets go ahead and fix the data in place now that we're on the background thread.
                        gibraltarPacket.FixData();
                    }

                    //and now fire our MessageDispatching event.
                    try
                    {
                        PacketEventHandler messageDispatching = MessageDispatching; // Snapshot our subscribers.
                        if (messageDispatching != null)
                        {
                            messageDispatching(this, new PacketEventArgs(packet));
                        }
                    }
                    catch (Exception)
                    {
                        Log.DebugBreak(); // Catch this in the debugger, but otherwise swallow any errors.
                    }
                }

                //If this is a header packet we want to put it in the header list now - that way
                //if any messenger recycles while we are writing to the messengers it will be there.
                //(Better to pull the packet forward than to risk having it in an older stream but not a newer stream)
                if (envelope.IsHeader)
                {
                    lock (m_HeaderPacketsLock) //MS doc inconclusive on thread safety of ToArray, so we guarantee add/ToArray safety.
                    {
                        m_HeaderPackets.Add((ICachedMessengerPacket)packet);
                        System.Threading.Monitor.PulseAll(m_HeaderPacketsLock);
                    }
                }

                // Data message or Command packet - either way, send it on to each messenger.
                foreach (IMessenger messenger in m_Messengers)
                {
                    //we don't want an exception with one messenger to cause us a problem, so each gets its own try/catch
                    try
                    {
                        messenger.Write(packet, writeThrough);
                    }
                    catch (Exception)
                    {
                        Log.DebugBreak(); // Stop in debugger, ignore in production.
                    }
                }

                //if this was a write through packet we need to let the caller know that it was committed.
                envelope.IsCommitted = true; //under the covers this does a pulse on the threads waiting on this envelope.
            }

            // Now that it's committed, finally send it to any Notifiers that may be subscribed.
            QueueToNotifier(packet);

            //we only need to do this here if the session file writer is disabled; otherwise it's doing it at the best boundary.
            if ((m_Configuration.SessionFile.Enabled == false) &&
                (packet.Sequence % 8192 == 0))
            {
                StringReference.Pack();
            }
        }
 public PacketHandlerPriorityContainer(PacketEventHandler handler, PacketHandlerPriority priority = PacketHandlerPriority.Normal)
 {
     Id       = Interlocked.Increment(ref idCounter);
     Handler  = handler;
     Priority = priority;
 }
示例#15
0
 /// <summary>
 /// Adds a handler to the PacketToSendEvent.
 /// </summary>
 /// <param name="handler">Handler for PacketToSendEvent</param>
 public void registerPacketEventHandler(PacketEventHandler handler)
 {
     this.PacketToSendEvent += handler;
 }
示例#16
0
文件: ModuleBase.cs 项目: nikes/Link
 protected void Register(uint packetId, PacketEventHandler handler, PacketHandlerPriority priority = PacketHandlerPriority.Normal)
 {
     Handlers[packetId]   = handler;
     Priorities[packetId] = priority;
 }
示例#17
0
        public virtual void AddHandler <T>(PacketEventHandler handler, int priority = 0) where T : GamePacket
        {
            var packetId = GamePacket.GetOnePacketIdentifier <T>();

            AddHandler(packetId, handler);
        }
 public PacketEventHandlerPriority(int id, int priority, PacketEventHandler handler)
 {
     Id       = id;
     Priority = priority;
     Handler  = handler;
 }
 public void RegisterEvent(PacketEventHandler handler)
 {
     Event += handler;
 }