tags:

views:

100

answers:

2
+1  Q: 

TCP Socket Piping

Suppose that you have 2 sockets(each will be listened by other TCP peers) each resides on the same process, how these sockets could be bound, meaning input stream of each other will be bound to output stream of other. Sockets will continuously carry data, no waiting will happen. Normally thread can solve this problem but, rather than creating threads is there more efficient way of piping sockets?

+1  A: 

If you need to connect both ends of the socket to the same process, use the pipe() function instead. This function returns two file descriptors, one used for writing and the other used for reading. There isn't really any need to involve TCP for this purpose.

Update: Based on your clarification of your use case, no, there isn't any way to tell the OS to connect the ends of two different sockets together. You will have to write code to read from one socket and write the same data to the other. Depending on the architecture of your process, you may or may not need an additional thread to do this work. For example, if your application is based on a select() loop, then creating another thread is not necessary.

Greg Hewgill
In fact these sockets will be listened by clients, so there needs to be sockets
whoi
It seems I misunderstood your use case. I'll update my answer.
Greg Hewgill
Are you saying socket select() function, can you make a clarification?
whoi
Yes, I am referring to the socket `select()` function. You didn't mention which language or framework you are using, so I have assumed something like C with a standard socket library (which applies to all common operating systems). A `select()` loop architecture arranges your program with a single main loop that calls `select()` watching for events to happen on any of the sockets opened by the application. When an event happens, your program will react to that by reading or writing the socket (and importantly, not blocking), then return to the main loop to wait for the next event.
Greg Hewgill
Okay, thanks for explanation.
whoi
A: 

You can avoid threads with an event queue within the process. The WP Message queue article assumes you want interprocess message passing, but if you are using sockets, you kind of are doing interprocess message passing over the same process.

Charles Stewart