예제 #1
0
        /// <summary>
        /// Асинхронный запуск сервера
        /// </summary>
        /// <returns></returns>
        public Task StartAsync()
        {
            return(Task.Factory.StartNew(() =>
            {
                try
                {
                    if (MessageEncryptionEnabled)
                    {
                        Console.WriteLine($"Server run on {Port} with encryption channel");
                    }
                    else
                    {
                        Console.WriteLine($"Server run on {Port}");
                    }

                    _listener.Start();

                    while (true)
                    {
                        TcpClient client = _listener.AcceptTcpClient();

                        Task.Factory.StartNew(() =>
                        {
                            var fluffyClient = new FluffyClient(client, this);

                            AddConnectedClient(fluffyClient);

                            StoreInit?.Invoke(fluffyClient);

                            NewClientConnected?.Invoke(fluffyClient);

                            fluffyClient.Disconnected += client1 => { ClientDisconnected?.Invoke(client1); };

                            fluffyClient.NewData += (data) =>
                            {
                                NewData?.Invoke(fluffyClient, data);
                            };

                            fluffyClient.NewPacket += (ref int id, PacketParser <Packet> parser, FluffyClient xFuffyClient) =>
                            {
                                NewPacket?.Invoke(ref id, parser, xFuffyClient);
                            };
                        });
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message + " " + e.StackTrace);
                }
            }));
        }
예제 #2
0
        private void OnRecieve(IAsyncResult state)
        {
            EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

            if (!open)
            {
                return;
            }

            try
            {
                ArtNetData recieveState = (ArtNetData)(state.AsyncState);

                if (recieveState == null)
                {
                    // Packet was invalid continue receiving
                    ReceiveArtNet();
                }
                recieveState.DataLength = EndReceiveFrom(state, ref remoteEndPoint);

                // Protect against UDP loopback where we recieve our own packets.
                if (LocalEndPoint != remoteEndPoint && recieveState.Valid)
                {
                    LastPacket = DateTime.Now;
                    var packet = ArtNetPacket.FromData(recieveState);
                    if (packet == null)
                    {
                        ReceiveArtNet();
                    }

                    NewPacket?.Invoke(this, new NewPacketEventArgs <ArtNetPacket>((IPEndPoint)remoteEndPoint, packet));
                }
            }
            catch (Exception ex)
            {
                UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, false));
            }
            ReceiveArtNet();
        }
예제 #3
0
        public bool Connect()
        {
            if (_client?.Connected == true)
            {
                return(true);
            }

            try
            {
                _client = new TcpClient();
                _client.Connect(_address, _port);

                _drs = new DataReceiveService(_client, this);


                Task.Factory.StartNew(() =>
                {
                    _drs.Disconnected += client =>
                    {
                        Disconnected?.Invoke();
                    };

                    _drs.NewData += (data) =>
                    {
                        NewData?.Invoke(data);

                        try
                        {
                            object packet = null;

                            int packetId = BitConverter.ToInt32(data.Take(4).ToArray(), 0);

                            NewPacket?.Invoke(ref packetId, (t) =>
                            {
                                using (MemoryStream ms = new MemoryStream(data.Skip(4).ToArray()))
                                    using (BsonReader reader = new BsonReader(ms))
                                    {
                                        JsonSerializer serializer = new JsonSerializer();

                                        packet = serializer.Deserialize(reader, t);
                                    }

                                return((Packet)packet);
                            }, this);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message + " " + e.StackTrace);
                        }
                    };

                    _drs.Run();
                });

                var waitPacket = SendPacketAndGetResponse <ConnectionRequest, ConnectionConfig>(new ConnectionRequest());

                if (waitPacket?.CryptoEnabled == true)
                {
                    RsaClientSide rsaClientSide = new RsaClientSide();

                    var publicKey = rsaClientSide.PublicKeyString;

                    var rsaHandshakeResponse =
                        SendPacketAndGetResponse <RsaHandshakeRequest, RsaHandshakeResponse>(
                            new RsaHandshakeRequest()
                    {
                        PublicKey = publicKey
                    });

                    if (rsaHandshakeResponse == null)
                    {
                        throw new Exception();
                    }

                    var decryptedData = rsaClientSide.Step2(rsaHandshakeResponse.EncryptedData);

                    Console.WriteLine($"Receive decrypted AES-256 Key: {Convert.ToBase64String(decryptedData)}");

                    Aes256Key = decryptedData;

                    var pinger = new PingService(this);
                    pinger.StartAsync();
                }
                else
                {
                    var pinger = new PingService(this);
                    pinger.StartAsync();
                }
            }
            catch (Exception e)
            {
                return(false);
            }

            return(true);
        }
예제 #4
0
 /// <summary>
 /// Raises an event that indicates a new packet has arrived.
 /// </summary>
 /// <param name="p">The arrived <see cref="Packet"/>.</param>
 protected void OnNewPacket(Packet p)
 {
     NewPacket?.Invoke(this, p);
 }
예제 #5
0
        private void ReceiveDataStart(int receiveBufferLength)
        {
            try
            {
                _disconnectTimer.Stop();
                _disconnectTimer.Start();

                _disconnectTimer.Elapsed += (sender, args) =>
                {
                    Console.WriteLine("Client disconnected by timeout");
                    CloseConnect();
                };

                using (NetworkStream stream = TcpClient.GetStream())
                {
                    while (TcpClient.Connected)
                    {
                        if (TcpClient.Available < HeaderLength)
                        {
                            Thread.Sleep(5);
                            continue;
                        }

                        int messageLength = ReceiveHeaderData(stream);

                        if (messageLength > _server.MaxReceivePacketLength)
                        {
                            CloseConnect();
                            return;
                        }

                        int remaining = messageLength;

                        byte[] finalDataBuffer = new byte[messageLength];

                        int index = 0;

                        while (remaining > 0)
                        {
                            if (remaining < receiveBufferLength)
                            {
                                receiveBufferLength = remaining;
                            }

                            while (TcpClient.Available < receiveBufferLength)
                            {
                                Thread.Sleep(5);
                            }

                            byte[] buffer = new byte[receiveBufferLength];

                            stream.Read(buffer, 0, receiveBufferLength);

                            for (int i = 0; i < buffer.Length; i++)
                            {
                                finalDataBuffer[index++] = buffer[i];
                            }

                            remaining -= receiveBufferLength;
                        }

                        if (Aes256Key != null)
                        {
                            finalDataBuffer = MyAes.DecryptBytes(finalDataBuffer, Aes256Key, MyAes.Iv);
                        }

                        Console.WriteLine("Readed from client bytes length " + (finalDataBuffer.Length));

                        if (ByteArrayCompare(finalDataBuffer, PingData))
                        {
                            Send(PongData);

                            _disconnectTimer.Stop();
                            _disconnectTimer.Start();

                            Console.WriteLine("Ping data received " + (messageLength + HeaderLength) + " bytes. Pong data sent");
                        }
                        else
                        {
                            NewData?.Invoke(finalDataBuffer);

                            try
                            {
                                object packet = null;

                                int packetId = BitConverter.ToInt32(finalDataBuffer.Take(4).ToArray(), 0);

                                if (_server.MessageEncryptionEnabled)
                                {
                                    if (this.Aes256Key == null)
                                    {
                                        if (packetId != -122030 && packetId != -42142)
                                        {
                                            Console.WriteLine("Пришел пакет, который не ожидался");
                                            continue;
                                        }
                                    }
                                }

                                NewPacket?.Invoke(ref packetId, (t) =>
                                {
                                    using (MemoryStream ms = new MemoryStream(finalDataBuffer.Skip(4).ToArray()))
                                        using (BsonReader reader = new BsonReader(ms))
                                        {
                                            JsonSerializer serializer = new JsonSerializer();

                                            packet = serializer.Deserialize(reader, t);
                                        }

                                    return((Packet)packet);
                                }, this);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message + " " + e.StackTrace);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // Debug
                Console.WriteLine(e.Message + " " + e.StackTrace);
            }
            finally
            {
                Disconnected?.Invoke(this);

                CloseConnect();
            }
        }