public override void SendPacket(T packet) { byte[] binary = packetConverter.ToBinary(packet); byte[] buffer = Slip.CreateSlipPacket(binary); stream.Write(buffer, 0, buffer.Length); }
// Read a packet protected byte[] ReadPacket() { if (!quitReceiver && stream != null) { if (stream is FileStream) { FileStream fileStream = (FileStream)stream; // Store last end position if (lastEnd == -1) { lastEnd = fileStream.Position; } // Deal with file truncation, by starting at the start of the file long end = fileStream.Length; if (end < lastEnd) { fileStream.Seek(0, SeekOrigin.Begin); packetBuffer.Clear(); lastEnd = fileStream.Position; } // Read any new bytes from the file if (end > lastEnd) { byte[] buffer = new byte[end - lastEnd]; int length = fileStream.Read(buffer, 0, buffer.Length); lastEnd += length; for (int i = 0; i < length; i++) { packetBuffer.Add((byte)buffer[i]); } } // Let's parse any packets for (; ;) { byte[] packet = Slip.ExtractSlipPacket(packetBuffer); if (packet == null) { break; } if (packet.Length > 0) { //Console.WriteLine("ReadPacket():"); //Console.WriteLine(Slip.HexDump(packet)); return(packet); } } // No packets Thread.Sleep(20); // short delay to prevent spinning waiting for file appends } else { for (; ;) { // LATER: Shame stream doesn't seem to support checking how many bytes are available without blocking int b = -1; try { b = stream.ReadByte(); } catch (TimeoutException) { } catch (IOException) { } catch (ObjectDisposedException) { } //catch (ThreadInterruptedException) { stream.Close(); break; } if (b == -1) { break; } packetBuffer.Add((byte)b); // Let's parse any packets for (; ;) { byte[] packet = Slip.ExtractSlipPacket(packetBuffer); if (packet == null) { break; } if (packet.Length > 0) { //Console.WriteLine("ReadPacket():"); //Console.WriteLine(Slip.HexDump(packet)); return(packet); } } } } } return(null); }