473,799 Members | 3,270 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

networkStream.R ead gets incomplete data

!NoItAll
297 Contributor
So I've been wrapped around the axle on this problem using the tcpClient and networkStream.
My code first sends a byte count (8 bytes) so the receiver knows exactly how much to expect. This works flawlessly. Subsequent transmissions would sometimes get everything, but with large records (I'm sending object(s) serialized as XML) the data would often get truncated.
I tried:

Expand|Select|Wrap|Line Numbers
  1. Dim RxSize as Integer = receiveBufferLength(networkStream)
  2. Dim RxBytes(RxSize) as Byte
  3. Do While tcpClient.Available < RxSize
  4.     Threading.Thread.Sleep(100)
  5. End While
  6.  
  7. RxBytes = networkStream.Read(RxBytes, 0, RxSize)
  8.  
But often the tcpClient.Avail able bytes was less than the RxSize and would NOT increment to the expected RxSize.

What I found is that once the tcpClient.Avail able bytes stopped incrementing I had go get them and then the underlying socket would begin adding new bytes to the buffer. A secondary read would get the rest.
I tried setting the tcpClient.Recei veBufferSize to RxSize - that did not help. I also set tcpClient.NoDel ay=True - again no help...
This seemed confusing but here is the code I wound up working out...

Expand|Select|Wrap|Line Numbers
  1. ' Get the stream
  2. Dim networkStream As NetworkStream = tcpClient.GetStream()
  3.  
  4. 'get the buffersize and set it from the data in the first transmission
  5. Dim RxSize As Integer = receiveBufferLength(networkStream)
  6. tcpClient.ReceiveBufferSize = RxSize
  7.  
  8. ' Read the stream into a byte array
  9. Dim rxBytes(rxSize) As Byte
  10.  
  11. Dim rxBits(0) As Byte
  12. Dim iBits As Integer = 0
  13. Dim iPos As Integer = 0
  14.  
  15. Dim Timeout As Integer = 0
  16.  
  17.  While iPos < rxSize
  18.     iBits = tcpClient.Available
  19.     ReDim rxBits(iBits)
  20.     networkStream.Read(rxBits, 0, iBits)
  21.     rxBits.CopyTo(rxBytes, iPos)
  22.     iPos += (rxBits.Length - 1)
  23.     Threading.Thread.Sleep(100)
  24.     Timeout += 1
  25.     If Timeout > 20 Then Exit While
  26.  End While
  27.  
  28.  
This does as many reads as necessary to get all of the bytes from the networkStream and concatenates it to my receive buffer (rxBytes). It allows for up to 21 times through the loop before giving up (I don't know if that's enough - but so far its never gone through more than twice)

So my question is:
what do people on this forum think of this approach? Does anyone have an idea for more efficient code?
Oct 13 '11 #1
0 1533

Sign in to post your reply or Sign up for a free account.

Similar topics

0
2415
by: Hai Ly Hoang \(MT00KSTN\) | last post by:
Hi, FileStream.Read(buf, offset, siz) will return when reaching the end of file or a block (size siz) can be read from the file. In the case of NetworkStream, it's more confusing. Now, consider this case: The server send a block of 15 letter A. At the time NetworkStream.Read is called (on client machine), the client machine has only received 3 letter A: Server (send): AAAAAAAAAAAAAAA Client (receive): AAA
1
1809
by: Napo | last post by:
Hi I use a c# method to open an excel file and to read it's data.But i find a problem that if i changed the excel file data manually by using excelapplication,the readed data by c# method isn't the modified data,it's old data still! I think that maybe caused by c# use a data cache . How to refresh it or how to read the true excel file data?I don't want close my app Thanks
2
5215
by: Brent Burkart | last post by:
Below is the error I am receiving. I have checked SQL Profiler and it is receiving the correct query which runs fine in Query Analyzer. Any ideas? Server Error in '/lockinsheet' Application. ---------------------------------------------------------------------------- ---- Invalid attempt to read when no data is present. Description: An unhandled exception occurred during the execution of the current web request. Please review the...
1
3541
by: Steve | last post by:
I'm working on a program that talks to the Yahoo chat servers. But I have run into a small problem and I'm not sure what to do next. After I successfully log into yahoo and receive my cookies I think login to their chat servers. It's at this point I am having the problem. When the following code executes: networkstream.Read(bytes, 0, CInt(tcpClient2.ReceiveBufferSize)) Dim returndata As String = Encoding.ASCII.GetString(bytes)
3
4701
by: Vijay | last post by:
Hi Folks, I having one issue, in my application I am going to use the server push for streaming the data by keeping the connection open. At client side, i am having the XMhttprequest object (i.e ActiveX object of IE). When the data comes, onreadystatechange method get callback on state 3 but it doesn't allow me to read the data from the object. It says 'The data necessary to complete this operation is not yet available'. Is it...
4
7576
by: DaveR | last post by:
I have a background thread to accept and process TCP/IP connections. When the application shuts down I want to gracefully terminate it. The thread will block in NetworkStream.Read() waiting for data. I expected that shutting down the TcpListener would unblock the Read() and cause an exception, or return 0 bytes. But it does not work. Relevant parts of the code are shown below. If a client connects, the stream blocks in its Read()...
4
12803
by: Cyron | last post by:
Hello Friends, When I make a call to NetworkStream.Read(byte buffer, int offset, int size) I have found that this method will block until size bytes have been read or the connection is closed. Is this the correct behavior? My MSDN documentation led me to believe that this function should block until at least 1 byte of data was available, the connection was closed, or size bytes of data had been read. Any comments or clarifications...
1
2426
by: Charles | last post by:
Hi, Is there a way to find out how many bytes NetworkStream Read/Write actually read/wrote when there is an exception (i.e. socket read/write timeout). Or, can I assume that if there is an exception that no bytes are read/written. Thanks, Charles.
10
9159
by: ohmmega | last post by:
hello out there, I use a thread data from a linuxserver. i ask for data, i read the data (fix in size) - so far so good. this works great for the first 61 datapackages, then my thread abruptly freezes, because of the read method. i can't locate the real reason. if I reconnect the tcpClient after each package it works fine, but after several minutes the linux programm quits (not my fault, not my code, not to change). has anybody any...
1
1896
Oodles Of Noodles
by: Oodles Of Noodles | last post by:
Hello fellow geeks I have a problem in my database iVB .Net program that is generating 'Error:Invalid attempt to read when no data is present.' The weird part is that when you call the page from another page the script works yielding the desired records BUT WHEN YOU CALL THE SCRIPT AGAIN WHEN ATTEMPTING TO CALL THE SAME PAGE (PASSING DIFFERENT PARAMETERS USING QUERYSTRING ) THE QUERY DOESN'T YIELD ANY DATA Sub PropertyView( )
0
9688
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9544
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10238
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10030
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9077
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6809
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4145
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.