Page 1 of 1

Binary stream using stdout/stdin

Posted: Mon Oct 17, 2016 9:09 pm
by Keya
the PB helpfile already has a good example for ReadConsoleData but i wanted to break it down into the client/server model to get my head around both ends of the task

Sender: reads a binary file (first cmdline parameter), uses WriteConsoleData to send it to StdOut

Code: Select all

#READBYTES=4096
OpenConsole()
sFile.s = ProgramParameter(0)
If sFile = ""
  PrintN("Usage: sender <filename>"):  End
EndIf  
hFile = ReadFile(#PB_Any, sFile, #PB_File_SharedRead|#PB_File_SharedWrite)
If hFile = 0
  Print("Couldn't read " + sFile)
Else  
  *buf = AllocateMemory(#READBYTES)
  Repeat
    nbytes = ReadData(hFile, *buf, #READBYTES)
    WriteConsoleData(*buf, nbytes)      ;binary version of Print(), nice!
  Until Eof(hFile)
  CloseFile(hFile)
EndIf
Receiver: executes the sender app (hidden) and reads from the StdIn pipe using ReadProgramData()

Code: Select all

#READBYTES=4096
OpenConsole()
*buf = AllocateMemory(#READBYTES)
Dumper = RunProgram("sender.exe", "binarytosend.dat", "", #PB_Program_Open | #PB_Program_Read | #PB_Program_Hide)
If Dumper
  While ProgramRunning(Dumper)
    If AvailableProgramOutput(Dumper)
      nbytes = ReadProgramData(Dumper, *buf, #READBYTES)
      ;PrintN(PeekS(*buf, nbytes))  ;or whatever buffer processing
    EndIf
    If Inkey()
      If RawKey() = 27: Break: EndIf   ;Escape key to allow graceful exit of loop
    EndIf
  Wend
  PrintN("Finished reading binary stream. Exitcode: " + Str(ProgramExitCode(Dumper)))
  CloseProgram(Dumper)
EndIf
Warning: I initially thought it might be useful for the Receiver app to call Delay(1) if AvailableProgramOutput()=0 (just to free up the CPU a little), but this actually resulted in missing a small amount of data. No problem if Delay isn't called.