Q:

tcl/tk - Can we redirect the tcl stdout to a socket?

I am trying to redirect my stdout and stderr output to a text widget and I tried Memchan to do it and it did not work.
The next option we are looking at is using sockets. Can we redirect tcl stdout to a socket? If yes, can you provide an example code to demonstrate that?

A:

Can you run in a subprocess? It's easy if you can:
socket -server accept 12345   ;# pick your own port number...
proc accept {channel host port} {
    exec [info nameofexecutable] realScript.tcl \
            <@$channel >@$channel 2>@$channel &
}
vwait forever                 ;# run the event loop to serve sockets...

This starts a Tcl subprocess executing realScript.tcl for each incoming socket connection, and arranges for stdin (<@) stdout (>@) and stderr (2>@) to be redirected to the socket. It also runs the subprocess in the background (final &) so that it doesn't block incoming connections. (You might want to check $host and $port for acceptability before running the subprocess.)
What's even better, in the subprocess Tcl will still auto-detect that it's dealing with sockets; the fconfigure command will be able to see the socket configuration (even if it can't change what port its talking to, of course).

