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)); }
/// <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); }