Handle() public method

public Handle ( Packet packet ) : Packet
packet Packet
return Packet
Esempio n. 1
0
        public async void Read()
        {
            try
            {
                while (true)
                {
                    var buffer    = new byte[2];
                    var bytesRead = await _nstream.ReadAsync(buffer, 0, 2);

                    if (bytesRead != 2)
                    {
                        throw new Exception("Wrong packet");
                    }

                    var length = BitConverter.ToInt16(buffer, 0);

                    buffer    = new byte[length];
                    bytesRead = await _nstream.ReadAsync(buffer, 0, length);

                    if (bytesRead != length)
                    {
                        throw new Exception("Wrong packet");
                    }

                    _packetHandler.Handle(new Packet(1, buffer), this);
                }
            }
            catch (Exception e)
            {
                Log.Error($"ServerThread: {e.Message}");
                Termination();
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Handle new connection messages
        /// </summary>
        /// <param name="connection">Connection that send the message</param>
        /// <param name="data">Message raw data</param>
        private void NewConnectionHandler(InputConnection connection, MemoryStream data)
        {
            try
            {
                List <Packet> messages     = PacketHandler.Handle(data);
                Packet        firstMessage = messages.FirstOrDefault();
                _logger.Trace($"Client => Server: {firstMessage?.ToString()}");

                switch (firstMessage?.Type) // FIX: RequestID is always an only packet?
                {
                case PacketType.HttpRequest:
                    if (this._httpServerPort > 0)
                    {
                        connection.Send(Encoding.ASCII.GetBytes(
                                            "HTTP/1.1 301 Moved Permanently\nLocation: http://" +
                                            this._localEndPoint.Address.ToString() +
                                            (this._httpServerPort != 80 ? ":" + this._httpServerPort.ToString() : "") +
                                            "\nConnection: close\n\n")); // TODO: Set public IP or domain
                    }
                    else
                    {
                        connection.Send(Encoding.ASCII.GetBytes(
                                            "HTTP/1.1 503 Service Unavailable\nConnection: close\n\nThis is not a web server"));
                    }
                    connection.Disconnect();
                    break;

                case PacketType.RequestID:
                    RequestIdPacket reqId     = firstMessage as RequestIdPacket;
                    Player          newPlayer = new Player(reqId?.Name, connection);

                    // TODO: Check bans. connection.Send(ResponseIdPacket.RejectPlayer().ToBinary());
                    this.AddPlayer(newPlayer);
                    break;

                default:
                    _logger.Warning(
                        $"Packet not expected on new connection from {connection.Ip}: {Enum.GetName(typeof(PacketType), firstMessage?.Type)}");
                    break;
                }

                if (messages.Count > 1)
                {
                    _logger.Warning("Multiple messages on new connection not expected.");
                }
            }
            catch (UnrecognizedPacketException ex)
            {
                _logger.Warning($"Unrecognized packet from client {connection.Ip}: {ex.Message}");
                connection.Disconnect();
            }
            catch (VersionNotFoundException ex)
            {
                _logger.Warning($"Protocol version mismatch from client {connection.Ip}: {ex.Message}");
                connection.Disconnect();
            }

            // Remove new connection handler. This isn't new already.
            connection.OnMessage -= this._newConnectionEventHandler;
        }
Esempio n. 3
0
        private static void ReceiveCallback(IAsyncResult AR)
        {
            Socket current = (Socket)AR.AsyncState;

            int received;

            try
            {
                received = current.EndReceive(AR);
                if (received > 0)
                {
                    byte[] recBuf = new byte[received];
                    Array.Copy(_Buffer, recBuf, received);
                    PacketHandler.Handle(recBuf, current);
                    if (current.Connected)
                    {
                        current.BeginReceive(_Buffer, 0, _BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("Client forcefully disconnected" + e.Message);
                current.Close(); // Dont shutdown because the socket may be disposed and its disconnected anyway
                _ClientSockets.Remove(current);
                return;
            }
        }
Esempio n. 4
0
        private void ReceiveCallback(IAsyncResult result)
        {
            ConnectionInfo connection = result.AsyncState as ConnectionInfo;

            try
            {
                Socket      clientSocket = connection.socket;
                SocketError response;
                int         buffSize = clientSocket.EndReceive(result, out response);

                if (response == SocketError.Success)
                {
                    byte[] packet = new byte[buffSize];
                    Array.Copy(connection.data, packet, packet.Length);

                    PacketHandler.Handle(packet, clientSocket);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Can't receive data from Client, {e.Message}");
            }
            finally
            {
                try
                {
                    connection.socket.BeginReceive(connection.data, 0, connection.data.Length, SocketFlags.None, ReceiveCallback, connection);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"{e.Message}");
                    connection.socket.Close();
                }
            }
        }
Esempio n. 5
0
        public void ReceiveCallBack(IAsyncResult resultConnection)
        {
            Socket clientSocket = (Socket)resultConnection.AsyncState;

            try
            {
                Thread threadDataElement = new Thread(new ThreadStart(() => {
                    int bufferLength = _socket.EndReceive(resultConnection);
                    byte[] packet    = new byte[bufferLength];
                    Buffer.BlockCopy(_buffer, 0, packet, 0, packet.Length);
                    ph.Handle(packet,
                              clientSocket);
                }));
                threadDataList.Add(threadDataElement);
                threadDataElement.Start();
            }
            catch (SocketException e)
            {
                Console.WriteLine("[-] Connexion had to be closed because the host ended the connection...");
                Environment.Exit(0);
            }

            _buffer = new byte[1024];
            _socket.BeginReceive(
                _buffer,
                0,
                _buffer.Length,
                SocketFlags.None,
                ReceiveCallBack,
                null
                );
        }
        /// <summary>
        /// ReceivedCallback when we receive something from Socket
        /// </summary>
        /// <param name="result"></param>
        private void ReceivedCallback(IAsyncResult result)
        {
            try
            {
                int    buffLength = _socket.EndReceive(result);
                byte[] packet     = new byte[buffLength];

                Array.Copy(_buffer, packet, packet.Length);

                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(packet);
                }

                // Handle packet
                robotOutputPackage = PacketHandler.Handle(packet, packet.Length);

                // Update UI
                PublishEventToUI();

                // Start receiving next package
                StartReceiving();
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Received calback exception message: {ex.Message}");
            }
        }
Esempio n. 7
0
        private void arrivedData(IAsyncResult iAr)
        {
            try
            {
                int DataLength = uSocket.EndReceive(iAr);

                if (DataLength > 1)
                {
                    byte[] packetBuffer = new byte[DataLength];
                    Array.Copy(dataBuffer, 0, packetBuffer, 0, DataLength);

                    /* Decode Packet */
                    for (int I = 0; I < packetBuffer.Length; I++)
                    {
                        packetBuffer[I] = (byte)(packetBuffer[I] ^ 0x96);
                    }

                    PacketHandler pHandler = PacketManager.parsePacket(packetBuffer);

                    if (pHandler != null)
                    {
                        pHandler.Handle(this);
                    }
                }

                uSocket.BeginReceive(dataBuffer, 0, dataBuffer.Length, SocketFlags.None, new AsyncCallback(arrivedData), null);
            }
            catch { disconnect(); }
        }
Esempio n. 8
0
 private void arrivedData(IAsyncResult iAr)
 {
     try
     {
         int num = this.uSocket.EndReceive(iAr);
         if (num <= 1)
         {
             //this.disconnect();
         }
         else
         {
             byte[] numArray = new byte[num];
             Array.Copy(this.dataBuffer, 0, numArray, 0, num);
             for (int i = 0; i < (int)numArray.Length; i++)
             {
                 numArray[i] = (byte)(numArray[i] ^ 195);
             }
             PacketHandler packetHandler = PacketManager.parsePacket(numArray);
             if (packetHandler != null)
             {
                 packetHandler.Handle(this);
             }
             this.uSocket.BeginReceive(this.dataBuffer, 0, (int)this.dataBuffer.Length, SocketFlags.None, new AsyncCallback(this.arrivedData), null);
         }
     }
     catch
     {
         this.disconnect();
     }
 }
Esempio n. 9
0
        private void ReceivedCallback(IAsyncResult result)
        {
            int buffLength = _socket.EndReceive(result);

            byte[] packet = new byte[buffLength];

            Array.Copy(_buffer, packet, packet.Length);

            // Read header for getting message size - TODO: proper implementation of this
            //int pacSize = BitConverter.ToInt32(new byte[] {packet[3], packet[2], packet[1], packet[0] }, 0);
            //byte[] pacBuffer = new byte[pacSize];
            //_socket.Receive(pacBuffer, pacSize, SocketFlags.None);

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(packet);
            }

            // Handle packet

            double[] rp = PacketHandler.Handle(packet, packet.Length);

            Application.Current.Dispatcher.Invoke(() => svm.UpdateUI(rp));
            //StartReceiving();
            _socket.Shutdown(SocketShutdown.Both);
            _socket.Close();
        }
Esempio n. 10
0
 void Update()
 {
     if (packetQeue.Count > 0)
     {
         handler.Handle(packetQeue[0], socket);
         packetQeue.RemoveAt(0);
     }
 }
Esempio n. 11
0
        private void OnReceiveCallback(IAsyncResult result)
        {
            _nstream.EndRead(result);

            byte[] buff = new byte[_buffer.Length];
            _buffer.CopyTo(buff, 0);
            _packetHandler.Handle(new Packet(1, buff), this);
            Read();
        }
Esempio n. 12
0
        private void ReceivedCallback(IAsyncResult result)
        {
            try
            {
                // we catch that connection we send and since AsyncState is a object so we set it as Socket to get connection
                Socket ListenerSocket = result.AsyncState as Socket;


                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                //StateObject state = (StateObject)reasult.AsyncState;
                //Socket handler = state.workSocket;

                //EndReceive is used to count the amount of data received
                int mBufferSize = ListenerSocket.EndReceive(result);
                //reciveDone.Set();
                //if (bufferSize == 58 || bufferSize == 40)
                //{

                //it is done to store to store the data in buffer to packet
                byte[] mPacket = new byte[mBufferSize];
                //reciveDone.Set();
                // Console.WriteLine("*********************** Listener" + IPAddress.Parse(((IPEndPoint)ListenerSocket.LocalEndPoint).Address.ToString())
                //   + "*********************** Speaker" + IPAddress.Parse(((IPEndPoint)ListenerSocket.RemoteEndPoint).Address.ToString()));

                // it is done to create a shadow clone of buffer before anyone uses it
                // this method stores the data in buffer to packet
                Array.Copy(mBuffer, mPacket, mPacket.Length);



                //Handle the packet
                PacketHandler.Handle(mPacket, mListenerSocket);

                ReceivedMessage.Set();

                FSM_Listener.BGPOpenMsgRecived(Variables.True);

                //}
                // else
                //{

                mBuffer = new byte[1024];
                ListenerSocket.BeginReceive(mBuffer, 0, mBuffer.Length, SocketFlags.None, ReceivedCallback, ListenerSocket);
                // }
            }
            catch (ObjectDisposedException ex)
            {
                // Don't care
                Console.WriteLine("Listener socket is closed");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Esempio n. 13
0
    public void OnPacket(object?sender, IByteReader reader)
    {
        ushort            op      = reader.Read <ushort>();
        PacketHandler <T>?handler = handlers.GetValueOrDefault(op);

        if (sender is T session)
        {
            handler?.Handle(session, reader);
        }
    }
Esempio n. 14
0
        /// <summary>
        /// Called whenever an onReceive event is received by the server, which signifies
        /// an incoming packet from an existing connection.
        /// </summary>
        /// <param name="session">The connection's session</param>
        /// <param name="data"></param>
        /// <param name="bytesRead"></param>
        private bool OnRecieve(ServerSession session, byte[] data, int bytesRead)
        {
            int packetLength = ((data[0] & 0xFF) + ((data[1] & 0xFF) << 8));
            int packetOpcode = ((data[2] & 0xFF) + ((data[3] & 0xFF) << 8));

            byte[] packetData = new byte[packetLength - 4];

            Array.Copy(data, 4, packetData, 0, packetLength - 4);

            PacketHandler handler = _packetManager.GetHandler(packetOpcode);

            // Handle the incoming packet
            return(handler.Handle(session, packetLength - 4, packetOpcode, packetData));
        }
Esempio n. 15
0
 public override bool HijackGetData(ref byte messageType, ref BinaryReader reader, int playerNumber)
 {
     try
     {
         if (PacketHandler.CheckBlockPacket(playerNumber, messageType, ref reader))
         {
             return(true);
         }
         // 处理原版消息的地方
         return(_packetHandler.Handle(messageType, ref reader, playerNumber));
     }
     catch (Exception ex)
     {
         CommandBoardcast.ConsoleError(ex);
     }
     return(false);
 }
Esempio n. 16
0
        void ReceivedCallback(IAsyncResult result)
        {
            try
            {
                Socket clientSocket = result.AsyncState as Socket;

                int bufSize = clientSocket.EndReceive(result);

                byte[] buf = new byte[bufSize];
                Buffer.BlockCopy(buffer, 0, buf, 0, bufSize);

                //handle
                PacketHandler.Handle(this, buf);

                buffer = new byte[Packet.bufferMaxLength];
                clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceivedCallback, clientSocket);
            }
            catch (Exception e)
            {
                ConnectionClosed(this, e);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Handle messages sended from a player
        /// </summary>
        /// <param name="player"></param>
        /// <param name="data"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void PlayerMessageHandler(Player player, MemoryStream data)
        {
            try
            {
                List <Packet> messages = PacketHandler.Handle(data);
                messages.ForEach((message) => _logger.Trace($"Player => Server: {message.ToString()}"));

                foreach (Packet message in messages)
                {
                    switch (message.Type)
                    {
                    case PacketType.RequestJoinZone:
                        this.HandleJoinZoneRequest(player, (RequestJoinZonePacket)message);
                        break;

                    case PacketType.RequestSetAlias:
                        player.SetAlias((message as RequestSetAliasPacket)?.Alias);
                        break;

                    default:
                        _logger.Warning($"Unrecognized message: {message.ToString()}");
                        throw new NotImplementedException();
                    }
                }
            }
            catch (UnrecognizedPacketException ex)
            {
                _logger.Warning($"Unrecognized packet from client {player.Connection.Ip}: {ex.Message}");
                player.Disconnect();
            }
            catch (PlayerRejectedException rejected)
            {
                _logger.Debug($"Player {player.Name} rejected: {rejected.Message}");
                // TODO: rejected.Player.SendMessage(rejected.Message);
                this.RemovePlayer(rejected.Player);
            }
        }
Esempio n. 18
0
        public async void ReadData(TcpClient tcpClient, ServerThreadPool cn)
        {
            _nstream  = tcpClient.GetStream();
            _client   = tcpClient;
            Connected = true;

            try
            {
                while (true)
                {
                    byte[] buffer    = new byte[2];
                    int    bytesRead = await _nstream.ReadAsync(buffer, 0, 2);

                    if (bytesRead != 2)
                    {
                        throw new Exception("Wrong packet");
                    }

                    short length = BitConverter.ToInt16(buffer, 0);

                    buffer    = new byte[length];
                    bytesRead = await _nstream.ReadAsync(buffer, 0, length);

                    if (bytesRead != length)
                    {
                        throw new Exception("Wrong packet");
                    }

                    Task.Factory.StartNew(() => _packetHandler.Handle(buffer.ToPacket(), this));
                }
            }
            catch (Exception e)
            {
                Log.Error($"ServerThread: {e.Message}");
                Termination();
            }
        }
Esempio n. 19
0
 private void OnPacket(ClientSocket client, byte[] buffer) => PacketHandler.Handle((Client)client.StateObject, buffer);
Esempio n. 20
0
        void AcceptNewConnection(IAsyncResult result)
        {
            if (listener.IsListening)
            {
                listener.BeginGetContext(AcceptNewConnection, null); //Сразу продолжаем прием новых запросов
            }
            else
            {
                return;
            }

            HttpListenerContext  context  = listener.EndGetContext(result);
            HttpListenerRequest  request  = context.Request;
            HttpListenerResponse response = context.Response;

            Out.WriteLine("{0} {1} {2}", DateTime.Now.ToString(), request.RemoteEndPoint, request.HttpMethod);

            try
            {
                PacketSerializer serializer = PacketSerializer.Create(request.ContentType);

                if (serializer == null)
                {
                    throw new NotSupportedException(); //вместо исключения должен быть корректный ответ об ошибке
                }
                //Читаем что нам прислали
                Packet <IPacketContent> packet = serializer.Deserialize <IPacketContent>(request.InputStream);

                if (packet == null)
                {
                    throw new ArgumentException();
                }

                //Подберем обработчик
                PacketHandler handler = PacketHandler.Create(packet.Version);
                handler.Out = Out;

                //Получаем результат
                Packet <IPacketContent> responsePacket = handler.Handle(packet);

                //И отправляем обратно
                using (MemoryStream mstream = new MemoryStream())
                {
                    serializer.Serialize(responsePacket, mstream);

                    response.ContentLength64 = mstream.Length;
                    response.StatusCode      = 200;

                    mstream.Position = 0;
                    mstream.CopyTo(response.OutputStream);
                }
            }
            catch (Exception ex)
            {
                Out.Write("General Exception");
                Out.Write(ex.Message);
                Out.Write(ex.StackTrace);
                response.StatusCode = 500;
            }
            finally
            {
                response.OutputStream.Close();
            }
        }
Esempio n. 21
0
 public void HandlePacket(NetIncomingMessage inc)
 {
     handler.Handle(inc);
 }
Esempio n. 22
0
        private void ProcessNetworkMessages()
        {
            NetIncomingMessage inc;

            while ((inc = client.ReadMessage()) != null)
            {
                switch (inc.MessageType)
                {
                //Report changes in connection status
                case NetIncomingMessageType.StatusChanged:
                    NetConnectionStatus status = (NetConnectionStatus)inc.ReadByte();
                    switch (status)
                    {
                    case NetConnectionStatus.Connected:
                        /*var message = new UpdatePlayerStateMessage(inc.SenderConnection.RemoteHailMessage);
                         * this.playerManager.AddPlayer(message.Id, message.Position, message.Velocity, message.Rotation, true);
                         * Console.WriteLine("Connected to {0}", inc.SenderEndPoint);*/
                        ConnectionSuccess("Connected to " + inc.SenderEndpoint);
                        break;

                    case NetConnectionStatus.Disconnected:
                        if (Entry.UserInterace != null && Entry.UserInterace.Chat != null)
                        {
                            Entry.UserInterace.Chat.Log("Lost connection to the server !");
                        }

                        string reason = "Unknown error !";
                        try
                        {
                            inc.ReadByte();
                            reason = inc.ReadString();
                        }
                        catch
                        {
                        }

                        ConnectionFailed(reason);
                        break;

                    case NetConnectionStatus.Disconnecting:
                    case NetConnectionStatus.InitiatedConnect:
                    case NetConnectionStatus.RespondedConnect:
                        Console.WriteLine(status.ToString());
                        break;
                    }
                    break;

                case NetIncomingMessageType.ConnectionApproval:

                    break;

                case NetIncomingMessageType.Data:
                    handler.Handle(inc);
                    break;

                case NetIncomingMessageType.VerboseDebugMessage:
                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.ErrorMessage:
                    Console.WriteLine(inc.ReadString());
                    break;
                }
                client.Recycle(inc);
            }
        }
Esempio n. 23
0
        public void Cycle()
        {
            if (!this._isStreaming)
            {
                return;
            }
label_2:
            int index1;

            while (true)
            {
                if (!this._hasNext)
                {
                    if (!this._stream.EndOfFile)
                    {
                        this._next    = this._last + this._stream.Compressed.ReadInt32();
                        this._last    = this._next;
                        this._hasNext = true;
                    }
                    else
                    {
                        break;
                    }
                }
                this._elapsed = Math.Max(this.GetTimeSample(), this._elapsed);
                if (this._elapsed >= this._next)
                {
                    this._hasNext = false;
                    index1        = (int)this._stream.Compressed.ReadByte();
                    if (index1 >= 0 && index1 < (int)byte.MaxValue)
                    {
                        PacketHandler packetHandler = PacketHandlers.m_Handlers[index1];
                        if (packetHandler != null)
                        {
                            int length = packetHandler.Length;
                            if (length < 0)
                            {
                                length = (int)this._stream.Compressed.ReadByte() << 8 | (int)this._stream.Compressed.ReadByte();
                            }
                            byte[] numArray1 = new byte[length];
                            int    num1      = 0;
                            byte[] numArray2 = numArray1;
                            int    index2    = num1;
                            int    num2      = 1;
                            int    index3    = index2 + num2;
                            int    num3      = (int)(byte)index1;
                            numArray2[index2] = (byte)num3;
                            if (packetHandler.Length < 0)
                            {
                                byte[] numArray3 = numArray1;
                                int    index4    = index3;
                                int    num4      = 1;
                                int    num5      = index4 + num4;
                                int    num6      = (int)(byte)(length >> 8);
                                numArray3[index4] = (byte)num6;
                                byte[] numArray4 = numArray1;
                                int    index5    = num5;
                                int    num7      = 1;
                                index3 = index5 + num7;
                                int num8 = (int)(byte)length;
                                numArray4[index5] = (byte)num8;
                            }
                            this._stream.Compressed.Read(numArray1, index3, length - index3);
                            packetHandler.Handle(new PacketReader(numArray1, 0, numArray1.Length, packetHandler.Length >= 0, (byte)index1, packetHandler.Callback.Method.Name));
                        }
                        else
                        {
                            goto label_14;
                        }
                    }
                    else
                    {
                        goto label_22;
                    }
                }
                else
                {
                    goto label_1;
                }
            }
            this.Stop();
            return;

label_1:
            return;

label_14:
            PlayUO.Debug.Trace("Bad packet {{ packetID: 0x{0:X2}; }}", (object)index1);
            try
            {
                while (!this._stream.EndOfFile)
                {
                    int num = this._stream.Compressed.ReadInt32();
                    if (num < 1000)
                    {
                        this._hasNext = true;
                        this._next    = this._elapsed + num;
                    }
                    else
                    {
                        this._stream.Seek(-3L, SeekOrigin.Current);
                    }
                }
                goto label_2;
            }
            catch
            {
                this.Stop();
                return;
            }
label_22:
            this.Stop();
        }
Esempio n. 24
0
        private void OnDataReceived(IAsyncResult iAr)
        {
            try
            {
                int bytesReceived = socket.EndReceive(iAr);

                if (bytesReceived > 0)
                {
                    byte[] packetBuffer = new byte[bytesReceived];

                    Buffer.BlockCopy(buffer, 0, packetBuffer, 0, packetBuffer.Length);
                    // Decrypt the bytes with the xOrKey.
                    for (int i = 0; i < bytesReceived; i++)
                    {
                        packetBuffer[i] ^= Core.Constants.xOrKeyReceive;
                    }

                    int oldLength = cacheBuffer.Length;
                    Array.Resize(ref cacheBuffer, oldLength + bytesReceived);
                    Array.Copy(packetBuffer, 0, cacheBuffer, oldLength, packetBuffer.Length);

                    int startIndex = 0; // Determs whre the bytes should split
                    for (int i = 0; i < cacheBuffer.Length; i++)
                    {
                        // loop trough our cached buffer.
                        if (cacheBuffer[i] == 0x0A)
                        {
                            // Found a complete packet
                            byte[] newPacket = new byte[i - startIndex]; // determ the new packet size.
                            for (int j = 0; j < (i - startIndex); j++)
                            {
                                newPacket[j] = cacheBuffer[startIndex + j]; // copy the buffer to the buffer of the new packet.
                            }

                            // Handle the packet instantly.
                            InPacket inPacket = new InPacket(newPacket);
                            if (inPacket.Id > 0)
                            {
                                PacketHandler <User> pHandler = NetworkTable.Instance.FindExternal(inPacket);
                                if (pHandler != null)
                                {
                                    try
                                    {
                                        pHandler.Handle(this, inPacket);
                                    }
                                    catch { /*Disconnect();*/ }
                                }
                                else
                                {
                                    Console.WriteLine("UNKNOWN PACKET :: " + newPacket);
                                }
                            }

                            startIndex = i + 1;
                        }
                    }

                    if (startIndex > 0)
                    {
                        byte[] fullCopy = cacheBuffer;
                        Array.Resize(ref cacheBuffer, (cacheBuffer.Length - startIndex));
                        for (int i = 0; i < (cacheBuffer.Length - startIndex); i++)
                        {
                            cacheBuffer[i] = fullCopy[startIndex + i];
                        }
                        fullCopy = null;
                    }

                    socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
                }
                else
                {
                    Disconnect();
                }
            }
            catch
            {
                Disconnect();
            }
        }
Esempio n. 25
0
        private void OnDataReceived(IAsyncResult iAr)
        {
            try
            {
                int bytesReceived = socket.EndReceive(iAr);

                if (bytesReceived > 0)
                {
                    byte[] packetBuffer = new byte[bytesReceived];

                    // Decrypt the bytes with the xOrKey.
                    for (int i = 0; i < bytesReceived; i++)
                    {
                        packetBuffer[i] = (byte)(this.buffer[i] ^ Core.Constants.xOrKeyReceive);
                    }

                    int oldLength = cacheBuffer.Length;
                    Array.Resize(ref cacheBuffer, oldLength + bytesReceived);
                    Array.Copy(packetBuffer, 0, cacheBuffer, oldLength, packetBuffer.Length);

                    int startIndex = 0;                                  // Determs where the bytes should split
                    for (int i = 0; i < cacheBuffer.Length; i++)
                    {                                                    // loop trough our cached buffer.
                        if (cacheBuffer[i] == 0x0A)
                        {                                                // Found a complete packet
                            byte[] newPacket = new byte[i - startIndex]; // determ the new packet size.
                            for (int j = 0; j < (i - startIndex); j++)
                            {
                                newPacket[j] = cacheBuffer[startIndex + j]; // copy the buffer to the buffer of the new packet.
                            }
                            packetCount++;
                            // Instant handeling
                            InPacket inPacket = new InPacket(newPacket);
                            if (inPacket != null)
                            {
                                if (inPacket.Id > 0)
                                {
                                    PacketHandler <User> pHandler = NetworkTable.Instance.FindExternal(inPacket);
                                    if (pHandler != null)
                                    {
                                        try
                                        {
                                            pHandler.Handle(this, inPacket);
                                        }
                                        catch (Exception e) { Log.Instance.WriteError(e.ToString()); }
                                    }
                                }
                            }
                            // Increase start index.
                            startIndex = i + 1;
                        }
                    }

                    if (startIndex > 0)
                    {
                        byte[] fullCopy = cacheBuffer;
                        Array.Resize(ref cacheBuffer, (cacheBuffer.Length - startIndex));
                        for (int i = 0; i < (cacheBuffer.Length - startIndex); i++)
                        {
                            cacheBuffer[i] = fullCopy[startIndex + i];
                        }
                        fullCopy = null;
                    }

                    socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);
                }
                else
                {
                    Disconnect();
                }
            }
            catch
            {
                Disconnect();
            }
        }