Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NetworkStream, is there something similar to DataReceived for a SerialPort? (C#)

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.

like image 361
Lloyd Powell Avatar asked Aug 06 '09 10:08

Lloyd Powell


1 Answers

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.

like image 184
Lloyd Powell Avatar answered Sep 30 '22 14:09

Lloyd Powell