views:

1096

answers:

2

Ok, so I'm a little confused as to why I can't find this anywhere, or if it doesn't exist then why have Microsoft not implemented it?

So here's my scenario, I have a NetworkStream, which has a lovely little boolean called DataAvailable, and what I need is an event, that jumps out and says "Hey, there's data available for you!" (because I'm lazy and I'd rather be told that there's data available than to keep asking "Alright, is there any data available?" over and over again until I get the response "Actually, this time there is").

Something similar a SerialPort (which has a nice event (DataReceived), that kindly informs me that data is being received from the port) would have been nice. But I'm using a Socket with a NetworkStream.

Point me in the correct direction if there's something blatently obvious that I'm missing, but if not, does this mean I am going to have to use some Data Binding on the DataAvailable property, and when it is set to true, to call my own 'home made' event/function? If this is going to be the way could you please give me a small example to get the ball rolling?

Edit
My perfect answer would be for someone to come along and explain to me how I can find/create something extremely similar to the DataReceived Event used with a SerialPort, but implemented for a Socket that is streaming via a NetworkStream!

Thanks in advance again, appreciated.

+1  A: 

There are no events in the NetworkStream class (see MSDN). NetworkStream inherits from Stream, therefore it follows the stream model, which is not based on events. If you need to receive data asynchronously, use the BeginRead method

Thomas Levesque
+2  A: 

Just to clarify Thomas' answer, with an explanation for anyone who isn't familliar with the BeginRead method and wants to understand the answer to this question, you can call:

AsyncCallBack MyCallBack = new AsynCallBack(DataReceived);
networkStream.BeginRead(buffer, offset, size, MyCallBack, MyObject);

then create the DataReceived function:

private void DataReceived(IAsynResult result)
  {
  //call receive functionality
  }

This will call DataReceived extremely similar to how the SerialPort.DataReceived event works.

ThePower
It's worth pointing out that you still need to call the .EndRead method to complete the read process correctly and get the data.
Andy