File: tcp-echo-server.tcl

package info (click to toggle)
srt 1.5.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,804 kB
  • sloc: cpp: 52,175; ansic: 5,746; tcl: 1,183; sh: 318; python: 99; makefile: 38
file content (51 lines) | stat: -rw-r--r-- 990 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/tclsh

proc SpawnEchoServer {fd host port} {
	fconfigure $fd -encoding binary -translation binary -blocking no -buffering none
	fileevent $fd readable "EchoBack $fd"
	# --- puts stderr "Connected: [fconfigure $fd -peername]"
}

proc EchoBack {fd} {

	# --- puts stderr "READ-READY"

	while 1 {

		# --- puts stderr "READING 4096"
		set r [read $fd 4096]
		if {$r == ""} {
			if {[eof $fd]} {
				# --- puts stderr "EOF. Closing"
				close $fd
				return
			}

			# --- puts stderr "SPURIOUS, giving up read"
			return
		}

		# Set blocking for a short moment of sending
		# in order to prevent losing data that must wait

		# --- puts stderr "SENDING [string bytelength $r] bytes"
		fconfigure $fd -blocking yes
		puts -nonewline $fd $r
		fconfigure $fd -blocking no

		if {[fblocked $fd]} {
			# --- puts stderr "NO MORE DATA"
			# Nothing more to read
			return
		}

		# --- puts stderr "AGAIN"

	}

}

socket -server SpawnEchoServer $argv
puts stderr "SERVER READY"

vwait tk