internal async void MessageLoop(TcpClient client, Func <byte[], Task> sender, Action <TcpClient, Exception> onCloseOrError) { async Task <bool> ReceiveBuffer(NetworkStream ns, byte[] buff) { int done = 0; while (done < buff.Length) { var read = await ns.ReadAsync(buff, done, buff.Length - done).ConfigureAwait(false); if (read == 0) { return(false); } done += read; } return(true); } try { var stream = client.GetStream(); while (client.Connected) { byte[] buffer = null; var lengthBytes = new byte[4]; if (!await ReceiveBuffer(stream, lengthBytes).ConfigureAwait(false)) { onCloseOrError(client, null); return; } var length = SafeBitConverter.ToInt32(lengthBytes, 0); if (length == 0) { continue; } buffer = new byte[length]; if (!await ReceiveBuffer(stream, buffer).ConfigureAwait(false)) { onCloseOrError(client, null); return; } var reply = Receive(buffer); if (reply != null) { await sender(reply).ConfigureAwait(false); } } } catch (Exception ex) { onCloseOrError(client, ex); } }
public object Deserialize(byte[] bytes) { var nameLength = SafeBitConverter.ToInt32(bytes, 0); var name = Encoding.UTF8.GetString(bytes, 4, nameLength); var type = TypeId.GetType(name); if (type == null) { throw new ApplicationException("Unable to read message type: " + name); } var spent = 4 + nameLength; var ser = new DataContractSerializer(type); using (var ms = new MemoryStream(bytes, spent, bytes.Length - spent)) return(ser.ReadObject(ms)); }