summaryrefslogtreecommitdiff
path: root/examples/tcp.server
blob: a86cd6364ee64b0b46b7c9417ff6a92be4daef6d (plain)
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
# Example of a udp server which sends a response

# Listen on port 20000. No host specified means 0.0.0.0
set s [socket stream.server 20000]

$s readable {
	# Clean up children
	os.wait -nohang 0
	set sock [$s accept addr]
	puts "Client address: $addr"

	# Make this server forking so we can accept multiple
	# simultaneous connections
	if {[os.fork] == 0} {
		$s close

		$sock buffering line

		# Get the request (max 80 chars) - need the source address
		while {[$sock gets buf] >= 0} {
			set buf [string trim $buf]
			puts -nonewline "read '$buf'"

			try {
				set result "$buf = [expr $buf]"
			} on error {msg} {
				set result "Error: $buf => $msg"
			}

			puts ", sending '$result'"

			# Send the result back to where it came from
			$sock puts $result
		}
	}

	$sock close
}

vwait done