How can I always capture the entire content of a network stream read in a
single operation of an asynchronous read callback function?
I have the following read callback function, in which I intend to read the
entire contents of a TCP data transmission and perform work on those
contents. It's working beautifully when reading any transmission of less
than 8192 bytes. However, when it encounters a transmission of greater
than 8192 bytes, it performs work on the first 8192 bytes, then runs the
function again for the subsequent 8192 bytes. When I examine the
networkStream object while stepping through the code it shows a
SystemNotSupported exception; "This stream does not support seek
operations."
I realize my exception handling sucks in the posted code. This is a
sandbox test for now, not production code.
I want to capture the entirety of the transmission in the callback
function before the work is performed on the data. How can I do this?
private void ReadCallback(IAsyncResult asyncResult)
{
Client client = asyncResult.AsyncState as Client;
if (client != null)
{
NetworkStream networkStream = client.NetworkStream;
int read;
try
{
read = networkStream.EndRead(asyncResult);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
if (read == 0)
{
return;
}
try
{
byte[] data = new byte[read];
Buffer.BlockCopy(client.Buffer, 0, data, 0, read);
string message =
win1252.GetString(data).TrimEnd('\u001a', '\r',
'\n'); //decode the transmission
//Do work on received message here...
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
No comments:
Post a Comment