Skip to content
dbohdan edited this page May 18, 2020 · 1 revision

By @rkeene. See https://chiselapp.com/user/rkeene/repository/karen/.

#! /usr/bin/env edonjs

/*
 * JavaScript using the Tcl runtime:
 */
server = runtime.socket('-server', function(sock, addr, port) {
    console.info("New connect from", addr, port, "as", sock);
    runtime.fileevent(sock, 'readable', function() {
        var line, e;

        try {
            line = runtime.gets(sock);
            if (runtime.eof(sock) && line === '') {
                console.info("EOF on sock", sock, "from", addr, port);

                runtime.close(sock);
                return;
            }
        
            console.debug("New data from", sock, ":", line);
        } catch (e) {
            console.error("Error processing sock", sock, ":", e);
            console.info("Closing sock", sock, "from", addr, port);
            runtime.close(sock);
        }
    });
}, 9313);


/*
 * Pure Tcl version:
 *
 * set server [socket -server {apply {{sock addr port} {
 *     puts "I> New connect from $addr $port as $sock"
 *     fileevent $sock readable [list apply {{sock addr port} {
 *         try {
 *             set line [gets $sock]
 *             if {[eof $sock] && $line eq ""} {
 *                 puts "I> EOF on sock $sock from $addr $port"
 *
 *                 close $sock
 *                 return
 *             }
 *
 *             puts "D> New data from $sock : $line"
 *         } on error e {
 *             puts "E> Error processing sock $sock : $e"
 *             puts "I> Closing sock $sock from $addr $port"
 *             close $sock
 *         }
 *     }} $sock $addr $port]
 * }}} 9313]
 */
Clone this wiki locally