简体   繁体   中英

Reading data from NetworkStream

I try to send a lot of data (an image) on a NetworkStream, yet it looks like a single Read is not enough- I'd like to try to read all the data sent on a NetworkStream, yet I have no idea how to do that. Also, I'd like to have this data as a bytes array byte[] . Any idea how to do that?

byte[] b = new byte[length];
int bytes = 0;
while (!GetNetworkStream().DataAvailable)
    Thread.Sleep(20); // Some delay
bytes = GetNetworkStream().Read(b, 0, b.Length);
MemoryStream ms = new MemoryStream();
ms.Write(b, 0, bytes);

I also tried the next code which does not seem to work:

using (NetworkStream stream = CommunicationHandler.GetStream())
{
    byte[] data = new byte[1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int numBytesRead;
        while ((numBytesRead = stream.Read(data, 0, data.Length)) > 0)
        ms.Write(data, 0, numBytesRead);
    }
}

As I can see you put in here some methods which you have created on your own and I suppose you don't have any problems in reading data. What you really need is some kind of handle at start of a new file because your socket should receiving data continiously.

It obviously depends on which image format you want to use, what you want to send. For PNG files you should read chapter 12 of this pdf file. Especially section 12. You could look for signature and extracting data from buffer if you hit sequence like this

(decimal)             137 80 78 71 13 10 26   10
(hexadecimal)          89 50 4e 47 0d 0a 1a   0a
(ASCII C notation)   \211 P  N   G \r \n \032 \n

Then you need to simply recreate png file. You must do the same with every type of file you send.

If you do not care about content of a file you could've create some data frame and put the data into payload (compressed and encrypted). Create own signature blahblahblah. The simplest example is Modbus. You can read more about it here .

edit

Reading the data of tcp stream is very simple. Just look at this code.

var receiveBufferSize = 512; // amount of bytes to read
try
{
    var buffer = new byte[receiveBufferSize];
    _tcpClient.GetStream().Read(buffer, 0, receiveBufferSize);
    // handle the received data chunk
}
catch (Exception e)
{
    // handle the error
    Debug.WriteLine(ex.Message);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM