Solved

Bidirectional nature of sockets

Posted on 2012-04-05
14
467 Views
Last Modified: 2012-06-21
Hi Experts,

Please correct me if I'm wrong on any of this and maybe throw in some goodies?

I would like to set up a client and server that communicate over a socket.  It is my understanding that I can write or read to this socket at any time, thus, the client and server may both contain a read and write thread (so 4 threads if client and server happen to be on the same machine).  Is is ok if the read thread polls and reads every so often while the write thread writes?  i.e., on one socket, are there two separate channels that don't affect eachother at all?

Thank you!
Mike
0
Comment
Question by:thready
  • 6
  • 3
  • 3
  • +2
14 Comments
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 215 total points
Comment Utility
That's all correct.  The read and write channels operate independently.

Typically you have two options when dealing with the read side:
(1) Continuously Poll and check some kind of "data available" flag/counter on the read stream to determine when to actually read buffered data.
(2) Place a blocking read call into another thread.  It will just sit there and won't return until data is received.  The blocking call is placed into a loop so that as long as there is data left in the buffer it will continue reading.  Since it is blocking, though, once all data has been read it will block again.
0
 
LVL 1

Author Comment

by:thready
Comment Utility
Excellent!  With option 2, it complicates termination/shutdown a lot though right?  How would you terminate that elegantly?
0
 
LVL 1

Author Comment

by:thready
Comment Utility
Just a timeout I guess- within the read (within the loop)?
0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 215 total points
Comment Utility
It depends on the framework you're using.  In C#, you can set the IsBackground() property of the Thread to True which causes it to automatically be terminated when the application is shut down.
0
 
LVL 20

Assisted Solution

by:BuggyCoder
BuggyCoder earned 72 total points
Comment Utility
adding to it, if you use tcplistener and call its start method, it will start a thread pool thread in background and start listening for the request.
Thread pool threads are much safer than opening your own threads are Threadpool is more effecient in handling threads....

here is an example:-
http://www.codeproject.com/Articles/2418/Making-Socket-Based-Application-Using-TcpListener
0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 215 total points
Comment Utility
You could also a Timeout feature if one is available.  This makes it essentially the same as polling in a loop (just be sure to check if there is data available before reading though).
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 71 total points
Comment Utility
>>Is is ok if the read thread polls and reads every so often while the write thread writes?

You can do that, but instead of polling, I'd use 'select()' to wait until data is available, i.e.

fd_set readfd;
timeval tv;

FD_ZERO(&readfd);
FD_SET(mysock,&readfd);

tv.tv_sec = TIME_IN_SEC;
tv.tv_usec = 0;

select(0,&readfd,NULL,NULL,&tv);

// data is now available

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 22

Assisted Solution

by:ambience
ambience earned 142 total points
Comment Utility
I would suggest against a thread (actually two threads per socket) design. This would inevitably lead to the antipattern "super-threading." Unless the number of sockets per program is going to be pretty small its easier to use a threaded server or client because of the simplicity, but if there are say 100 sockets you have 200 threads. Of course most of the time they'd be sleeping but still this isnt scalable beyond a certain degree.

I would recommend two additional patterns to look into,

- The Reactor pattern elegantly implemented by POCO here http://pocoproject.org/docs/Poco.Net.SocketReactor.html

The idea here is that theres a reactor object that watches (using select() internally or any other mechanism) multiple sockets, and your supplied delegate is called back for IO events. The reactor is supposed to be intelligent enough to adapt to growing needs. I have a SocketReactor that uses a grow-able thread group internally and a single thread handles 64 sockets. SocketReactor is good because it is easy to make it portable if you only use the posix API for sockets.

- Use the boost asio package http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/tutorial/tutdaytime7.html

Very easy to use abstraction over Asynchronous socket IO and uses IO Completion ports on Windows which makes it really scalable. Once you get past the basic hurdles of thinking in terms of asynchronous design, its pretty easy to use.
0
 
LVL 1

Author Comment

by:thready
Comment Utility
ambience, I agree with you, but I'm looking at a maximum of about 6-8 threads.  I have data-intensive reads and writes and I want them setup on a live socket that exists for the lifetime of each pair.  Once communication starts, there's a lot of data that goes back and forth and it's a bit in the need for speed.  If the connection is established, I only want to do that once.  I still need time to mull over the answers...  Thanks everyone!
0
 
LVL 22

Expert Comment

by:ambience
Comment Utility
>>  I have data-intensive reads and writes and I want them setup on a live socket that exists for the lifetime of each pair.  Once communication starts, there's a lot of data that goes back and forth and it's a bit in the need for speed.

Single thread per socket isnt necesarily going to be faster; there are so many factors that each would affect. I dont think any of the Reactor or IO completion based design would result in slowdown either. Depending upon how intelligent the internal design is the Reactor may sort of starve some sockets if say socket at index 0 is always active (has IO). But like I said, it depends upon the internals.

Threaded servers on the other hands are somewhat easier to code (though easy is a relative term).
0
 
LVL 1

Author Comment

by:thready
Comment Utility
I'm trying to find out which library to use that would simplify the client to use sockets with.  My goal is to have a bread-and-butter standard c++ socket on the client side.  Does anyone know if I use the standard library for sockets, so that I can easily drop this code into an iPad project as well as on a windows machine inside a native MFC application?
0
 
LVL 22

Assisted Solution

by:ambience
ambience earned 142 total points
Comment Utility
Nope - unless you are willing to wait till the next C++ standard comes out and is fully supported across the compiler landscape.

Sockets haven't made into STL yet ... but there are a lot of cross platform toolkits out there that should compile fine for iPad. Boost and POCO - both are cross platform.
0
 
LVL 1

Author Comment

by:thready
Comment Utility
POCO- right.  You said the magic word!  I really like POCO - I'll have to give it a try that way.
0
 
LVL 1

Author Closing Comment

by:thready
Comment Utility
Thanks everyone for the terrific help!
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now