Vivek Jha
Vivek Jha

Reputation: 1580

Concurrent TCP Server in Tcl

I have to write a TCP Server for my legacy application (standalone) to create a client - server interface for it.

I am planning to write pre-forked (can't user threads because of thread safety issues) concurrent server. I need following two things.

Q. A simple example program (may be an echo-server) explaining concerns and ingredients of a pre-forked concurrent server.

Q. Server will exchange data in JSON format. How to configure client socket, so that server know properly whether the client has completely written the json on channel or it is still in the process of writing.

Upvotes: 1

Views: 1232

Answers (1)

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

Why use threads or forks? Just use Tcl's event-driven model.

proc accept {sock host port} {
    fconfigure $sock -blocking 0 -buffering line
    fileevent $sock readable [list readsock $sock]
}

proc readsock {sock} {
    global sockbuf
    if {[read $sock data] < 0} {
       if {[eof $sock]} {
           # Socket was closed by remote
           unset sockbuf($sock)
           close $sock
           return
       }
    }
    append sockbuf($sock) $data\n
    # Check if you got all the necessary data. For Tcl lists, use [info complete]
    if {[info complete $sockbuf($sock)]} {
        set data $sockbuf($sock)
        unset sockbuf($sock)
        # process data
        puts $sock $data
    }
}

socket -server accept 12345
vwait forever; # This will enter the event loop.

If you really need (or want) to use Threads, thread safety is also not a problem in Tcl.
But using forks usually end up in reimplementing more or less the thread API.

If you really want to fork, then here are some of the problems that you will encounter:

  1. You have to communicate with the children. I suggest using pipes.
  2. You have to pass the socket from the master to the other children. While this might be possible with unix domain sockets at C level, but I don't know about any Tcl extension that can do that.
  3. You have to write the pool stuff yourself (or use a C library for that).

IMHO it is not worth all the needed effort for forks.

Upvotes: 3

Related Questions