--- /dev/null
+#! /usr/local/bin/tclsh8.4
+
+#######
+# Script should be called with at least one argument: port number
+# The second (optional) argument is used for debugging
+# ./exec_server port_number [debug]
+# ./exec_server 2547
+
+if { [llength $argv] == 0 || ! [string is integer [lindex $argv 0]] } {
+ puts stderr \
+ "Script should be called with one argument, server's port number:\n\
+ ./exec_server 2547"
+ exit 2
+}
+
+set server_port [lindex $argv 0]
+
+set debug_output false
+if { [llength $argv] == 2 || [lindex $argv 1] == "debug" } {
+ set debug_output true
+}
+
+
+#######
+# Exec_Server --
+# Open the server listening socket and enter the Tcl event loop
+#
+# Arguments:
+# port The server's port number
+
+proc Exec_Server {port} {
+ set s [socket -server ExecAccept $port]
+ vwait forever
+}
+
+#######
+# Exec_Accept --
+# Accept a connection from a new client.
+# This is called after a new socket connection
+# has been created by Tcl.
+#
+# Arguments:
+# sock The new socket connection to the client
+# addr The client's IP address
+# port The client's port number
+
+proc ExecAccept {sock addr port} {
+ global client
+
+ # Record the client's information
+ puts "Accept $sock from $addr port $port"
+ set client(addr,$sock) [list $addr $port]
+
+ fconfigure $sock -buffering full
+
+ # Set up a callback for when the client sends data
+ fileevent $sock readable [list Exec_command $sock]
+}
+
+#######
+# Exec_command --
+# This procedure is called when the server
+# can read data from the client
+#
+# Arguments:
+# sock The socket connection to the client
+
+proc Exec_command {sock} {
+ global client server_port debug_output
+
+ # Check end of file or abnormal connection drop,
+ # then send result of exec command back to the client.
+
+ if {[eof $sock] || [catch {gets $sock line}]} {
+ close $sock
+ puts "Close $client(addr,$sock)"
+ unset client(addr,$sock)
+ } else {
+ if { $line == "Kraj" } {
+ puts "Kraj rada."
+ puts $sock "Kraj"
+ close $sock
+ exit 0
+ }
+ if { $debug_output } { puts "$server_port/Kom >$line<" }
+ if { [llength $line] == 0 } {return}
+ catch {eval exec $line} odg
+ if { $debug_output } { puts "$server_port/Odg: $odg" }
+ puts $sock $odg
+ puts $sock "Kraj"
+ ;# prije: flush $sock
+ catch {flush $sock} rez
+ if { $rez != "" } {
+ puts "Socket closed on remote.\n$rez"
+ }
+ }
+}
+
+Exec_Server $server_port
+