Posted to tcl by Napier at Sun Feb 14 04:36:36 GMT 2016view pretty

proc ConnectSocket {ip port} {
  puts "Open Socket"
  set socketID [::socket $ip $port ]
  puts "Listen for Events"
  chan configure $socketID \
    -buffering none \
    -translation auto \
    -blocking false \
    -encoding "utf-8"
  
  set data "Hey Coroutine!"
  set count 0
  set future [ coroutine subroutine[incr count] apply {data {
    puts "Procedure Called!"
    set myVar 0
    
    set socketID [ yield [info coroutine] ]
    while {true} {
      puts "Start While Loop"
      puts "Future Executed!"
      puts "Data Provided is $data"
      puts "Invoked: $myVar times"
      switch -- $myVar {
        0 {
            puts "Process One!  We login"
            puts $socketID "lutron\r\n"
        }
        1 { 
            puts "Process Two!  We send password"
            puts $socketID "integration\r\n"
        }
      }
      set socketID [ yield [incr myVar] ]
    }
  }} $data ]
    
    
  chan event $socketID writable [ coroutine write${socketID} apply {socketID {
    yield [info coroutine]
    puts "Socket is still open!"
    chan event $socketID writable {}
    set context [info frame [info frame]]
    puts "Done Evaluating Writable Event"
    
  }} $socketID ]
  
  puts "Original Procedure Continues!"
  
  puts "... Next Event Saga Here ... "
  
  chan event $socketID readable [ coroutine read${socketID} apply { {socketID future} {
    
    yield [info coroutine]
    try {
      while {[gets $socketID line] >= 0} {
        puts "Received"
        puts $line
      }
      puts "Continue"
      set data [read -nonewline $socketID]
      puts "Read Result"
      puts $data
    } on error {result options} {
      puts "Uh-Oh!"
      puts $result
      puts $options
    } finally {
      puts "Call Future"
      set linesRead [ $future $socketID ]
      
      puts "We have read $linesRead lines from the Socket"
      
      #close $socketID
    }
    
  }} $socketID $future ]
  
}