示例#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
 public PendingData(TcpClient client, NetObject obj)
 {
     this.Client  = client;
     this.NObject = obj;
     this.Deleted = false;
 }
示例#4
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();
            });
        }
示例#5
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);
        }