package require tcl::transform::observe

proc writable {sock} {
    chan event $sock writable {}
    chan configure $sock -translation {crlf lf} -blocking 0 -buffering full -encoding binary
    chan event $sock readable [list readable $sock]
    set ::status "connected"
}

proc readable {sock} {
    set readCount [chan gets $sock line]
    if {$readCount < 0} {
        if {[eof $sock]} { 
            puts "Connection aborted"
            chan event $sock readable {}
            set ::msg "closed"
        }
        return
    }
    set ::msg $line
}

set sock [socket -async localhost 4400]
chan event $sock writable [list writable $sock]
vwait ::status
puts "Status=$status"
tcl::transform::observe $sock stdout ""

puts -nonewline $sock "Hello1\r\nHello2\r\n"
flush $sock

vwait ::msg
puts "Got $msg"

puts "pending input before pop: [chan pending input $sock]"
chan pop $sock
puts "pending input after pop: [chan pending input $sock]"
after 100 {set ::forever 1}
vwait forever ;# crashes here

close $sock
puts DONE
