Problem : I send data from the server to the client (both on the local machine) and the client does not have time to process / receive some of the data into the buffer. Sometimes it happens that it manages to process everything, but more often it does not. Conducted a test with the Windows client built-in telnet, he always manages to accept and withdraw everything. I tried to make a sending delay in the form of Thread.Sleep (50) and as a result the client began to keep up, but is this the way out?
Next code.
Code for sending messages on the server side:
public async Task Send<T, U>(Packet<T, U> message) { var buffer = message?.ToBytes(); if (buffer?.Length > 0) { var guid = Guid.NewGuid(); var countSemgment = Math.Ceiling(buffer.Length / (double)BufferSize); for (int index = 0; index < countSemgment; index++) { var bytes = AddGuid(buffer.Skip(index * BufferSize).Take(BufferSize).ToArray(), guid); await _stream.WriteAsync(bytes, 0, bytes.Length); } } } Guid is needed to identify a message if data is larger than the buffer size
Client code that accepts incoming messages:
private async void Receive() { byte[] buffer = new byte[BufferSize]; try { while (true) { var count = await _stream.ReadAsync(buffer, 0, buffer.Length); RaiseEventMessegaReceive(buffer, count); } } catch (Exception e) { Dispose(); } } The code to call the RaiseEventMessageReceive event at the client:
protected virtual void RaiseEventMessegaReceive(byte[] data, int count) { MsgReceivEvent?.Invoke(this, new MessageReceiveEventArgs(data, count)); } I tie this event to the event:
public async void PacketExecute(object o, MessageReceiveEventArgs msg) { await PacketHandler(msg.Data, msg.Count); } And the code itself handler incoming data
private async Task PacketHandler(byte[] data, int count) { await Task.Run(() => { try { Packet packet; using (BinaryReader br = new BinaryReader(new MemoryStream(data.Take(count).ToArray()))) { byte[] msg; var guid = new Guid(br.ReadBytes(16)); Console.WriteLine($@"Message Guid = {guid}"); if (PacketDictionary.TryGetValue(guid, out packet)) { msg = br.ReadBytes(count - guid.ToByteArray().Length); packet.Add(msg); } else { var groupCommand = br.ReadByte(); var command = br.ReadByte(); var dataLen = br.ReadInt32(); msg = dataLen > bufferSize - _service_len ? br.ReadBytes(bufferSize - _service_len) : br.ReadBytes(dataLen); packet = new Packet(guid, groupCommand, command, msg, dataLen); packet.PacketReadyEvent += PacketReadyExecute; packet.PacketFailEvent += PacketFailExecute; packet.StatusChange(); } PacketDictionary.AddOrUpdate(guid, packet, (g, p) => packet); } } catch (Exception e) { Console.WriteLine(e); throw; } }); }