From: Brian Candler Date: 2003-05-17T23:58:43+09:00 Subject: Re: TCP Sockets On Sat, May 17, 2003 at 10:24:34PM +0900, Dominik Werder wrote: > I tell you what I wanna do: > > I got two application servers with multiple threads each to handle > requests. A Request on one server could need data from the second server. > But I don't want to create a new connection each time. So I wanna have one > steady connection and when one or more threads need data from the other > server, they can send their packets right through this one connection. Like > telecommunications networks (ATM?): The packets are mixed together, send > through the line and extracted on the other end. In that scenario, the easiest thing to do is open a connection to the remote server, run a separate thread for each *incoming* connection, then whenever one of those threads wants to communicate with the remote server, it "grabs" the outgoing connection, uses it, and releases it. "grabs" in this case means takes a Mutex, so that none of the other threads can use it until it has finished. You could also write your application a single thread: in that case you need to select() on all the incoming fds, receive any messages or part-messages which are available, append the part-messages to buffers for each incoming stream, and when one of these buffers has a full message then you process it as necessary. If you need to maintain separate state for each connection then you'll need an explicit array of objects that hold state. It's a lot lower-level and a lot harder work. On the other hand, if you write your incoming-connection handler as a thread, then it can be written in a simple linear style - accept request, do something, send response - without having to keep an explicit array of connections, array of buffers, array of state variables etc. Cheers, Brian.