tcp-echo-server.tcl 990 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/tclsh
  2. proc SpawnEchoServer {fd host port} {
  3. fconfigure $fd -encoding binary -translation binary -blocking no -buffering none
  4. fileevent $fd readable "EchoBack $fd"
  5. # --- puts stderr "Connected: [fconfigure $fd -peername]"
  6. }
  7. proc EchoBack {fd} {
  8. # --- puts stderr "READ-READY"
  9. while 1 {
  10. # --- puts stderr "READING 4096"
  11. set r [read $fd 4096]
  12. if {$r == ""} {
  13. if {[eof $fd]} {
  14. # --- puts stderr "EOF. Closing"
  15. close $fd
  16. return
  17. }
  18. # --- puts stderr "SPURIOUS, giving up read"
  19. return
  20. }
  21. # Set blocking for a short moment of sending
  22. # in order to prevent losing data that must wait
  23. # --- puts stderr "SENDING [string bytelength $r] bytes"
  24. fconfigure $fd -blocking yes
  25. puts -nonewline $fd $r
  26. fconfigure $fd -blocking no
  27. if {[fblocked $fd]} {
  28. # --- puts stderr "NO MORE DATA"
  29. # Nothing more to read
  30. return
  31. }
  32. # --- puts stderr "AGAIN"
  33. }
  34. }
  35. socket -server SpawnEchoServer $argv
  36. puts stderr "SERVER READY"
  37. vwait tk