Reputation: 1580
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
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:
IMHO it is not worth all the needed effort for forks.
Upvotes: 3