// $Id: echo.ici,v 1.0 2003/01/03 11:26:00 dada Exp $
// http://dada.perl.it/shootout
//
// contributed by Tim Long

/*
 * This is a thread based version of the client-server echo test.
 * sys.fork() is available on UNIX-like systems, but is not core
 * language, and is not available on Windows.
 */
n = argv[1] ? int(argv[1]) : 1;
data = "Hello there sailor\n";

static
echo_client(n, port)
{
    sock := net.connect(net.socket("tcp/ip"), port);
    for (i := 0; i < n; ++i)
    {
        net.send(sock, data);
        if ((ans := net.recv(sock, nels(data))) != data)
            printf("received \"%s\", expected \"%s\"", ans, data);
    }
    net.close(sock);
    return 1;
}

ssock = net.listen(net.bind(net.socket("tcp/ip"), 0));
client = thread(echo_client, n, net.getportno(ssock));
csock = net.accept(ssock);
t = 0;
while (str = net.recv(csock, nels(data)))
{
    net.send(csock, str);
    t += nels(str);
}
waitfor(client.result; client)
    ;
printf("server processed %d bytes\n", t);