Пример #1
0
        /// <summary>
        /// Deserialize an object from its raw net data and make received.
        /// </summary>
        /// <param name="rawDataJson">The just-recieved data.</param>
        /// <param name="socket">The socket where the data comes from.</param>
        /// <returns>The NetObject gaven by the json.</returns>
        internal static NetObject Receive(string rawDataJson, Socket socket)
        {
            NetData <NetObject> data = JsonConvert.DeserializeObject <NetData <NetObject> >(rawDataJson);
            NetObject           obj  = JsonConvert.DeserializeObject(data.Data, data.Type) as NetObject;

            OnReceive?.Invoke(obj, data.Type, socket);
            return(obj);
        }
Пример #2
0
        public static NetObject Receive(Socket client, ManualResetEvent resetEvent = null)
        {
            byte[] sizeInfo = new byte[sizeof(int)];
            client.Receive(sizeInfo);
            int actualDataSize = BitConverter.ToInt32(sizeInfo, 0);

            byte[] data = new byte[actualDataSize];

            int totalread = 0, currentread = sizeof(int);

            while (totalread < actualDataSize && currentread > 0)
            {
                currentread = client.Receive(data,
                                             totalread,               //offset into the buffer
                                             data.Length - totalread, //max amount to read
                                             SocketFlags.None);
                totalread += currentread;
            }

            resetEvent?.Set();

            return(NetObject.Receive(NetData <NetDummy> .Encoding.GetString(NetData <NetDummy> .Decompress(data)), client));
        }
Пример #3
0
        protected void LoopListeningAsync()
        {
            Task.Run(async() =>
            {
                while (this.Connected)
                {
                    LoopResetEvent.WaitOne();
                    if (!this.Connected)
                    {
                        this.Disconnect("#server_disconnection_timeout");
                    }
                    LoopResetEvent.Reset();

                    Task.Run(async() =>
                    {
                        try
                        {
                            NetObject obj = await NetData <NetDummy> .ReceiveDataAsync(this.Client.Client, LoopResetEvent)
                                            .ConfigureAwait(true); //ReceiveDataAsync(this.Client.Client).Result;


                            if (this.Connected)
                            {
                                if (obj is NetKick kick)
                                {
                                    Disconnect(kick.Reason, true);
                                    return;
                                }

                                if (obj is NetDummy)
                                {
                                }
                                else
                                {
                                    Task.Run(() =>
                                    {
                                        OnServerDataReceived?.Invoke(obj);

                                        lock (PendingDataLocker) PendingData.Add(obj);
                                    });
                                }
                            }
                        }
                        catch (System.IO.InvalidDataException e)
                        {
                        }
                        catch (AggregateException e)
                        {
                            foreach (Exception exc in e.InnerExceptions)
                            {
                                if (exc is SocketException se)
                                {
                                    Connected = false;
                                    LoopResetEvent.Set();
                                }
                            }

                            if (Connected)
                            {
                                Debug.LogError("Multiple errors while receiving data: " + e);
                                LoopResetEvent.Set();
                            }
                        }
                        catch (SocketException se)
                        {
                            Connected = false;
                            LoopResetEvent.Set();
                        }
                        catch (Exception e)
                        {
                            Debug.LogError("Error while receiving data: " + e);
                            LoopResetEvent.Set();
                        }
                    });
                }

                //Debug.Log("stopped checking data.");

                //Disconnect();
            });
        }
Пример #4
0
        /// <summary>
        /// Wait for received data asynchronously. Used by <see cref="LoopListening(TcpClient)"/>.
        /// </summary>
        /// <param name="client">The socket to listen to.</param>
        /// <returns>The received <see cref="NetObject"/></returns>
        protected async Task <NetObject> ReceiveDataAsync(Socket client)
        {
            NetObject netobj = null;

            await Task.Run(() =>
            {
                byte[] sizeInfo = new byte[sizeof(int)];

                int totalread = 0, currentread = 0;
                currentread   = totalread = client.Receive(sizeInfo);

                while (totalread < sizeInfo.Length && currentread > 0)
                {
                    currentread = client.Receive(sizeInfo,
                                                 totalread,                   //offset into the buffer
                                                 sizeInfo.Length - totalread, //max amount to read
                                                 SocketFlags.None);

                    totalread += currentread;
                }

                int messageSize = 0;

                //could optionally call BitConverter.ToInt32(sizeinfo, 0);
                messageSize |= sizeInfo[0];
                messageSize |= (((int)sizeInfo[1]) << 8);
                messageSize |= (((int)sizeInfo[2]) << 16);
                messageSize |= (((int)sizeInfo[3]) << 24);

                byte[] data = new byte[messageSize];

                //read the first chunk of data
                totalread   = 0;
                currentread = totalread = client.Receive(data,
                                                         totalread,               //offset into the buffer
                                                         data.Length - totalread, //max amount to read
                                                         SocketFlags.None);

                //if we didn't get the entire message, read some more until we do
                while (totalread < messageSize && currentread > 0)
                {
                    currentread = client.Receive(data,
                                                 totalread,               //offset into the buffer
                                                 data.Length - totalread, //max amount to read
                                                 SocketFlags.None);
                    totalread += currentread;
                }

                LoopResetEvent.Set();

                try
                {
                    netobj = NetObject.Receive(NetData <NetDummy> .Encoding.GetString(NetData <NetDummy> .Decompress(data)), client);
                }
                catch (Exception e)
                {
                    Debug.LogError("Transmission error or decompressing error.");
                    netobj = new NetDummy();
                }
            }).ConfigureAwait(true);

            return(netobj);
        }
Пример #5
0
        /// <summary>
        /// Reads all incoming data from a client while <see cref="Running"/> is set to true.
        /// <br>Adds received data to <see cref="PendingData"/></br>
        /// </summary>
        /// <param name="client">The connected client to listen to.</param>
        protected void LoopListening(TcpClient client)
        {
            Task.Run(async() =>
            {
                while (this.Running)
                {
                    NetObject obj = new NetDummy();;

                    try
                    {
                        obj = await NetData <NetDummy> .ReceiveDataAsync(client.Client).ConfigureAwait(true);
                    }
                    catch (NullReferenceException ne)
                    {
                        //Debug.LogError("Unknown error while receiving data from client: " + ne);
                        break;
                    }
                    catch (ObjectDisposedException obje)
                    {
                        //Debug.LogError("Unknown error while receiving data from client: " + obje);
                        break;
                    }
                    catch (SocketException se)
                    {
                        //Debug.LogError("Unknown error while receiving data from client: " + se);
                        break;
                    }
                    catch (System.IO.InvalidDataException de)
                    {
                    }
                    catch (Exception e)
                    {
                        Debug.LogError("Unknown error while receiving data from client: " + e);
                    }

                    if (obj is NetDummy)
                    {
                        continue;
                    }
                    else if (client != null && this.Running)
                    {
                        OnClientDataReceived?.Invoke(client, obj);

                        lock (PendingDataLocker)
                        {
                            PendingData.Add(new PendingData(client, obj));
                        }
                    }

                    /*try
                     * {
                     *  NetObject obj = await NetData<NetDummy>.ReceiveDataAsync(client.Client).ConfigureAwait(true);
                     *
                     *  if (obj is NetDummy)
                     *  {
                     *      continue;
                     *  }
                     *
                     *  if (client != null && this.Running)
                     *  {
                     *      lock (PendingDataLocker)
                     *      {
                     *          OnClientDataReceived?.Invoke(client, obj);
                     *          PendingData.Add(new PendingData(client, obj));
                     *      }
                     *  }
                     * }
                     * catch(SocketException skte) {}
                     * catch(ObjectDisposedException obje) {}
                     * catch(Exception e)
                     * {
                     *  Debug.LogError("Error on receiving infos from client: " + e);
                     *  break;
                     * }*/
                }
            });
        }