Question

I'm coding a simple TCP client/server in VB.NET to transfer files of all sizes. I decided to use System.Net.Sockets's command SendFile to transfer the bytes through the socket.

On the receiving side, my code to retrieve the bytes works fairly well, but occasionally the transfer randomly stops.

I figured out that by putting a small sleep delay between retrieving the next block of data makes the transfers 100% stable.

My code to retrieve the data (until there is no data available) is simplified as this:

While newSocket.Available > 0
    Threading.Thread.Sleep(100)
    newSocket.ReceiveFrom(data, Remote)
End While

I really hate using that sleep delay and figure there must be a proper method/function to retrieve data from SendFile?

Was it helpful?

Solution

Socket.Available returns the total number of bytes that have been received so far that have not yet been read. Therefore, if you read the data faster than its coming in (which is quite possible on a slow network), there will be no more data to read even though the client is still in the middle of sending the data.

If the client makes a new connection to the server for each file it sends, you could simply change it to something like this:

While newSocket.Connected
    If newSocket.Available > 0 Then
        newSocket.ReceiveFrom(data, Remote)
    End If
End While

However, I would suggest using the asynchronous calls, instead, such as BeginReceive. Then, your delegate will be called as soon as there is data to be processed, rather than waiting in a constant loop. See this link for an example:

http://msdn.microsoft.com/en-us/library/dxkwh6zw.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top