Posted to tcl by Bradipo at Mon Jul 29 00:39:19 GMT 2024view pretty

proc readbytes {chan n b} {
  puts stdout "[clock format [clock seconds]]\
    readbytes $chan $n [binary encode hex $b]"
  if {[string length $b] == 2} {
    fileevent $chan readable [list readmorebytes $chan $n $b]
  } else {
    if {[eof $chan]} {
      fileevent $chan readable {}
      catch {close $chan}
      puts stderr "short read readbytes"
    } else {
      append b [read $chan 1]
      fileevent $chan readable [list readbytes $chan $n $b]
    }
  }
}

proc readmorebytes {chan n b} {
  puts stdout "[clock format [clock seconds]]\
    readmorebytes $chan $n [binary encode hex $b]"
  if {[string length $b] == $n} {
    fileevent $chan readable {}
    catch {close $chan}
    puts stdout "[clock format [clock seconds]]\
      got $n bytes [binary encode hex $b]"
  } else {
    if {[eof $chan]} {
      fileevent $chan readable {}
      catch {close $chan}
      puts stderr "short read readmorebytes"
    } else {
      append b [read $chan 1]
      fileevent $chan readable [list readmorebytes $chan $n $b]
    }
  }
}

proc doreceive {} {
  set fd [open /dev/urandom rb]
  fconfigure $fd -translation binary -blocking 0
  fileevent $fd readable [list readbytes $fd 8 ""]
}

proc receive {} {
  puts stdout "[clock format [clock seconds]] starting receive"
  doreceive
  puts stdout "[clock format [clock seconds]] rescheduling receive"
  after 10000 receive
}

receive

------------------------------------------------------------------------

Sun Jul 28 18:38:55 MDT 2024 starting receive
Sun Jul 28 18:38:55 MDT 2024 rescheduling receive
Sun Jul 28 18:38:55 MDT 2024 readbytes file4 8 
Sun Jul 28 18:38:55 MDT 2024 readbytes file4 8 7c
Sun Jul 28 18:38:55 MDT 2024 readbytes file4 8 7cef
Sun Jul 28 18:38:55 MDT 2024 readmorebytes file4 8 7cef
Sun Jul 28 18:38:55 MDT 2024 readmorebytes file4 8 7cef86
Sun Jul 28 18:38:55 MDT 2024 readmorebytes file4 8 7cef8663
Sun Jul 28 18:38:55 MDT 2024 readmorebytes file4 8 7cef8663a9
Sun Jul 28 18:38:55 MDT 2024 readmorebytes file4 8 7cef8663a9d8
Sun Jul 28 18:38:55 MDT 2024 readmorebytes file4 8 7cef8663a9d8bf
Sun Jul 28 18:38:55 MDT 2024 readmorebytes file4 8 7cef8663a9d8bff5
Sun Jul 28 18:38:55 MDT 2024 got 8 bytes 7cef8663a9d8bff5