473,749 Members | 2,626 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Concurrent reader/writer threads on single socket

I have what I imagine is a well-known .Net networking problem, but even
though I've Googled for some time I've not yet come across a thread
where this has been fully explained...

There is a fairly common idiom (at least in the Java/UNIX/Win32 worlds)
where a socket connection is established and the program then utilises
two threads: one dedicated to reading from the socket and the other one
concurrently writing to the socket - both using blocking i/o. These
two streams of data are probably related, but the protocol is arranged
to allow pipelining of requests so that the full-duplex nature of the
socket can be fully utilised.

What I'd like to know most of all is whether this pattern is supported
in .Net. A secondary question is, if it's not supported, then how do
people cope with the additional complexity that the asynchronous
beginXXX/endXXX methods introduce.

To start with, I note from the Microsoft documentation [1] that the
Socket class is thread-safe, so it would be reasonable to assume that
what is valid for a Winsock socket is also valid for a .Net socket.
However, the same documentation states that if you need to access the
socket in a multi-threaded program you should use the asynchronous
methods. Even so, I think the document leaves some element of doubt as
to whether concurrent access by a separate reader and writer thread is
allowed (especially as it is such a common pattern in other
environments).

In order to follow this pattern, I would expect to see something like
the following (in C#)

NetworkStream ns = new NetworkStream(s ocket);
BinaryWriter writer = new BinaryWriter(ns );
BinaryReader reader = new BinaryReader(ns );
startReaderThre ad(reader);
startWriterThre ad(writer);

Now, a further inspecation of the Micorosft documentation reveals that
NetworkSocket [2] is not safe for concurrent access. I can understand
this as this class could potentially have some internal state (such as
a buffer) which would make multithreaded access unsafe. In that case,
perhaps we should modify the example to use two separate
NetworkStreams. e.g.:

BinaryWriter writer = new BinaryWriter(ne w NetworkStream(s ocket));
BinaryReader reader = new BinaryReader(ne w NetworkStream(s ocket));
...

This seems reasonable, the output stream would hold a separate buffer
to the input stream and everything is fine.

Certainly the above is possible, and in my test program it appears to
work (most of the time). But I believe it may not be correct because
my test program occasionally reads invalid input from it's reader - and
I can only imagine this is due to some data corruption at the stream
level.

So, on to the second part of my question: how does one go about
converting an application that's been designed to use blocking I/O and
layered streams to the asynchronous model? We have many message
parsing routines, all of which expect a stream as input and each
routine works on the expectation that it will read the data it needs
from the stream and then return. I'd love to know how this model could
be changed to use asynchrous i/o without greatly adding to the
complexity. I realise this may not be a simple question to answer
(hopefully someone will tell me that part (1) is okay so there's no
need).

Thanks in advance.
Rob Lugt

[1]
http://msdn2.microsoft.com/en-us/lib...ts.socket.aspx
[2]
http://msdn2.microsoft.com/en-us/lib...orkstream.aspx

Oct 20 '06 #1
6 6447
You don't have to use the asynchronous (beginXXX/endXXX ) calls to get the
effect of asynchronous IO. You can work directly with the Socket class
(implements the Berkely socket interface), fire up your own threads, and
make blocking calls on the socket. I haven't tried doing simultaneous reads
and writes, each on their own thread, but I think it ought to work - the
receive and send buffers ought to be logically separate. I don't believe the
Sockets class is inherently thread safe, but it should be ok so long as you
serialize your reads or writes to the socket on the same thread.

The sockets class is a thin wrapper over the Winsock implementation.

<ro*****@gmail. comwrote in message
news:11******** **************@ i42g2000cwa.goo glegroups.com.. .
>I have what I imagine is a well-known .Net networking problem, but even
though I've Googled for some time I've not yet come across a thread
where this has been fully explained...

There is a fairly common idiom (at least in the Java/UNIX/Win32 worlds)
where a socket connection is established and the program then utilises
two threads: one dedicated to reading from the socket and the other one
concurrently writing to the socket - both using blocking i/o. These
two streams of data are probably related, but the protocol is arranged
to allow pipelining of requests so that the full-duplex nature of the
socket can be fully utilised.

What I'd like to know most of all is whether this pattern is supported
in .Net. A secondary question is, if it's not supported, then how do
people cope with the additional complexity that the asynchronous
beginXXX/endXXX methods introduce.

To start with, I note from the Microsoft documentation [1] that the
Socket class is thread-safe, so it would be reasonable to assume that
what is valid for a Winsock socket is also valid for a .Net socket.
However, the same documentation states that if you need to access the
socket in a multi-threaded program you should use the asynchronous
methods. Even so, I think the document leaves some element of doubt as
to whether concurrent access by a separate reader and writer thread is
allowed (especially as it is such a common pattern in other
environments).

In order to follow this pattern, I would expect to see something like
the following (in C#)

NetworkStream ns = new NetworkStream(s ocket);
BinaryWriter writer = new BinaryWriter(ns );
BinaryReader reader = new BinaryReader(ns );
startReaderThre ad(reader);
startWriterThre ad(writer);

Now, a further inspecation of the Micorosft documentation reveals that
NetworkSocket [2] is not safe for concurrent access. I can understand
this as this class could potentially have some internal state (such as
a buffer) which would make multithreaded access unsafe. In that case,
perhaps we should modify the example to use two separate
NetworkStreams. e.g.:

BinaryWriter writer = new BinaryWriter(ne w NetworkStream(s ocket));
BinaryReader reader = new BinaryReader(ne w NetworkStream(s ocket));
...

This seems reasonable, the output stream would hold a separate buffer
to the input stream and everything is fine.

Certainly the above is possible, and in my test program it appears to
work (most of the time). But I believe it may not be correct because
my test program occasionally reads invalid input from it's reader - and
I can only imagine this is due to some data corruption at the stream
level.

So, on to the second part of my question: how does one go about
converting an application that's been designed to use blocking I/O and
layered streams to the asynchronous model? We have many message
parsing routines, all of which expect a stream as input and each
routine works on the expectation that it will read the data it needs
from the stream and then return. I'd love to know how this model could
be changed to use asynchrous i/o without greatly adding to the
complexity. I realise this may not be a simple question to answer
(hopefully someone will tell me that part (1) is okay so there's no
need).

Thanks in advance.
Rob Lugt

[1]
http://msdn2.microsoft.com/en-us/lib...ts.socket.aspx
[2]
http://msdn2.microsoft.com/en-us/lib...orkstream.aspx

Oct 21 '06 #2

David Levine wrote:
You don't have to use the asynchronous (beginXXX/endXXX ) calls to get the
effect of asynchronous IO. You can work directly with the Socket class
(implements the Berkely socket interface), fire up your own threads, and
make blocking calls on the socket. I haven't tried doing simultaneous reads
and writes, each on their own thread, but I think it ought to work - the
receive and send buffers ought to be logically separate.
Thanks David - this is what I expected. But my occasional program
crashes make me suspect that this might not be the case. I wonder
could anyone from the Microsoft .Net Networking team confirm this is
supported?

Oct 21 '06 #3
What kind of crashes?

"Rob Lugt" <ro*****@gmail. comwrote in message
news:11******** **************@ i3g2000cwc.goog legroups.com...
>
David Levine wrote:
>You don't have to use the asynchronous (beginXXX/endXXX ) calls to get
the
effect of asynchronous IO. You can work directly with the Socket class
(implements the Berkely socket interface), fire up your own threads, and
make blocking calls on the socket. I haven't tried doing simultaneous
reads
and writes, each on their own thread, but I think it ought to work - the
receive and send buffers ought to be logically separate.

Thanks David - this is what I expected. But my occasional program
crashes make me suspect that this might not be the case. I wonder
could anyone from the Microsoft .Net Networking team confirm this is
supported?

Oct 21 '06 #4

David Levine wrote:
What kind of crashes?
I'm pretty sure that occasionally the value read from the socket reader
is different from the value that was sent by the sender, which would
indicate some kind of buffer corruption is occurring. It only occurs
when the program is under heavy load (and never when running within the
debugger) - which is why I suspect the thrreading model.

Oct 21 '06 #5
I wrote:
David Levine wrote:
What kind of crashes?

I'm pretty sure that occasionally the value read from the socket reader
is different from the value that was sent by the sender, which would
indicate some kind of buffer corruption is occurring. It only occurs
when the program is under heavy load (and never when running within the
debugger) - which is why I suspect the thrreading model.
I'm delighted to say that I've found a bug in the test program which
was almost certainly causing these read errors - and it wasn't due to
multi-threading but was caused by the program running faster than the
socket could provide data. I'm sorry for misleading the group.

So I think I can take it that the dual thread concurrent reader/writer
model does indeed work in .Net. I'd still very much like to see
Micorosft document this as a valid case.

Best regards
~Rob

Oct 21 '06 #6
DC
I have used the concurrent blocking reader/writer model extensively and
confirm that it is fine. I presume you are not simply seeing the effect of
write blocks not matching read blocks? tcp (if thats what you are using)
makes no guarentee of message boudries.

"Rob Lugt" <ro*****@gmail. comwrote in message
news:11******** **************@ i3g2000cwc.goog legroups.com...
>
David Levine wrote:
>What kind of crashes?

I'm pretty sure that occasionally the value read from the socket reader
is different from the value that was sent by the sender, which would
indicate some kind of buffer corruption is occurring. It only occurs
when the program is under heavy load (and never when running within the
debugger) - which is why I suspect the thrreading model.

Oct 21 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3281
by: Gonçalo Rodrigues | last post by:
Hi, My setup is the following: I have socket s from which I want to read and write. So I made the following set up: There is a thread whose only job is to read. Any data read (from recv call) is just passed to (some) Queue. This thread is "owned" by a second thread waiting on a Queue for write requests. The thread just pops these from the Queue, and calls the send method from the socket. This thread also takes care of closing the...
17
10040
by: PyPK | last post by:
Hi I am looking for a simple tiff Image reader/writer in python.Can anyone point me to the right one.
5
4231
by: Russell Warren | last post by:
Does anyone know the scope of the socket.setdefaulttimeout call? Is it a cross-process/system setting or does it stay local in the application in which it is called? I've been testing this and it seems to stay in the application scope, but the paranoid side of me thinks I may be missing something... any confirmation would be helpful.
2
2613
by: Jonas Hei | last post by:
Is it safe to call socket.BeginSendTo and socket.BeginSendFrom on a single instance of Socket from two different threads running simultaneously? This is required because I need to listen on a certain URI and I need to send outgoing messages from that local socket something like this: public class Communicator { Socket skt = new Socket(AddressFamily.InterNetwork,
10
3599
by: Hunk | last post by:
Hi I would like some ideas on way to solve the concurrency issue. The problem is , I have an object say X which multiple readers need to access and also to update. They do so by say two functions : // simplistic view of the problem Read() { return X; }
0
8997
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8833
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9568
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6801
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4709
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4881
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2794
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2218
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.