• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 434
  • Last Modified:

NetworkStream and TcpClient : read only necessary datas

Hi Experts,

I need to read my networkstream, so I do like this:
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
networkStream.Read(bytes, 0, tcpClient.ReceiveBufferSize);

The problem is that the buffer size (8192) > my datas(20).
So, finally I read the networkstream and I get a string length=8192 instead of a string length=20.

How can I get the only datas I need ?

Thanks in advance for your help.
0
noulouk
Asked:
noulouk
1 Solution
 
Expert1701Commented:
The System.Net.Sockets.NetworkStream.Read method returns an integer reporting the number of bytes that were actually received:

  byte[] bytes = new byte[tcpClient.ReceiveBufferSize];

  int received = networkStream.Read(bytes, 0, tcpClient.ReceiveBufferSize);
  byte[] data = new byte[received];
  System.Array.Copy(bytes, data, received);

In this example, if 20 bytes of data were actually received, the 'data' array would have only have 20 elements.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now