#!/usr/local/bin/tclsh
# $Id: echo.tcl,v 1.1 2001/03/02 04:05:06 doug Exp $
# http://www.bagley.org/~doug/shootout/

# from: Kristoffer Lawson

proc newClient {sock addr port} {
    fconfigure $sock -buffering line
    set r [gets $sock]
    set rLength 0
    while {![eof $sock]} {
    incr rLength [string length $r]
    # Extra increase because [gets] doesn't return \n
    incr rLength
    puts $sock $r
    set r [gets $sock]
    }
    puts "server processed $rLength bytes"
    exit
}


proc runClient {n addr port} {
    set sock [socket $addr $port]
    fconfigure $sock -buffering line
    set msg "Hello there sailor"

    while {$n} {
    puts $sock $msg
    if {[gets $sock] != $msg} {
        error "Received different message: $r."
    }
    incr n -1
    }
}


set n [lindex $argv 0]

if {[llength $argv] < 2} {
    socket -server newClient 10000
    exec tclsh83 [info script] $n client &
    vwait forever
} else {
    runClient $n localhost 10000
}