Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to transfer files through TCP/IP in a VB.NET application and I have problem about the size of transferred file here is the codes:

Server:

VB
Imports System.Net.Sockets
Imports System.Text
Imports System.Net
Imports System.ComponentModel
Class MainWindow
    Dim Timer As New Stopwatch
    Dim LocalAddr As IPAddress
    Dim ServerSocket As TcpListener
    Dim RequestCount As Integer
    Dim ClientSocket As TcpClient
    Dim BW As New BackgroundWorker With {.WorkerSupportsCancellation = True}
    Dim BWAccept As New BackgroundWorker With {.WorkerSupportsCancellation = True}
    Dim FileStreamer As New      System.IO.FileStream("C:\Users\m_shahgholi\Desktop\New folder\test.dcm", IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.ReadWrite)

   Private Sub DoWorker(sender As Object, e As System.ComponentModel.DoWorkEventArgs)

      While (True)
        Try
            RequestCount = RequestCount + 1

            Dim networkStream As NetworkStream = ClientSocket.GetStream()


            Dim bytesFrom(ClientSocket.ReceiveBufferSize) As Byte
            networkStream.Read(bytesFrom, 0, CInt(ClientSocket.ReceiveBufferSize))


            'IO.File.WriteAllBytes("C:\temp\1.dcm", bytesFrom)
            Me.Dispatcher.Invoke(Sub()
                                     If ClientSocket.Available <> 0 Then
                                         TextBoxClientBufferSize.Text =  ClientSocket.Available.ToString
                                     End If


                                     FileStreamer.Write(bytesFrom, 0,  CInt(ClientSocket.ReceiveBufferSize))

                                 End Sub)
            'Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
            'dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
            'msg("Data from client -  " + dataFromClient)
            Dim serverResponse As String = "Server response " +  Convert.ToString(RequestCount) + "$"
            Dim sendBytes As Byte() = Encoding.UTF8.GetBytes(serverResponse)
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            networkStream.Flush()
            msg(serverResponse)
            'networkStream.Close()
        Catch ex As Exception
            Exit While
        End Try
    End While

End Sub

Private Sub CompleteWorker(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs)

    ClientSocket.Close()
    ServerSocket.Stop()
    msg("exit")
    StackPanelClient.Visibility = Windows.Visibility.Collapsed
    Timer.Stop()

    TextBoxClientBufferSize.Text = Timer.Elapsed.ToString
    FileStreamer.Close()
End Sub
Sub msg(ByVal mesg As String)
    mesg.Trim()
    Me.Dispatcher.Invoke(
        Sub()
            RichTextBoxRecivedText.AppendText(mesg + vbCrLf)
            RichTextBoxRecivedText.ScrollToEnd()
        End Sub)
End Sub

   Private Sub ButtonStart_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonStart.Click
    TextBoxServerIP.Text = System.Net.Dns.GetHostByName(Dns.GetHostName()).AddressList(0).ToString()
    LocalAddr = IPAddress.Parse(TextBoxServerIP.Text)
    ServerSocket = New TcpListener(LocalAddr, 8888)

    ServerSocket.Start()
    msg("Server Started")
    WaitForClientProgressIndicator.Visibility = Windows.Visibility.Visible
    LabelServerIP.Visibility = Windows.Visibility.Visible
    TextBoxServerIP.Visibility = Windows.Visibility.Visible
    WaitForClientProgressIndicator.Start()
    StackPanelServer.Background = Brushes.Red
    AddHandler BWAccept.DoWork, AddressOf AcceptDoWorker
    AddHandler BWAccept.RunWorkerCompleted, AddressOf AcceptCompleteWorker
    BWAccept.RunWorkerAsync()
End Sub

Private Sub AcceptDoWorker(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
    ClientSocket = ServerSocket.AcceptTcpClient
    ServerSocket.Server.ReceiveBufferSize = 8192 * 2
    ClientSocket.ReceiveBufferSize = 8192 * 2

End Sub

Private Sub AcceptCompleteWorker(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs)
    msg("Accept connection from client")
    Me.Dispatcher.Invoke(Sub() TextBoxClientBufferSize.Text = ClientSocket.ReceiveBufferSize)
    RequestCount = 0
    RichTextBoxRecivedText.Background = Brushes.Black
    RichTextBoxRecivedText.Foreground = Brushes.WhiteSmoke
    WaitForClientProgressIndicator.Visibility = Windows.Visibility.Collapsed
    WaitForClientProgressIndicator.End()
    ButtonStart.Visibility = Windows.Visibility.Collapsed
    ButtonStop.Visibility = Windows.Visibility.Visible
    AddHandler BW.DoWork, AddressOf DoWorker
    AddHandler BW.RunWorkerCompleted, AddressOf CompleteWorker
    Timer.Start()
    BW.RunWorkerAsync()
    TextBoxClientIP.Text = DirectCast(ClientSocket.Client.RemoteEndPoint, IPEndPoint).Address.ToString
    StackPanelClient.Visibility = Windows.Visibility.Visible
    StackPanelServer.Background = Brushes.WhiteSmoke
End Sub

Private Sub ButtonStop_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonStop.Click
    ClientSocket.Close()
    ServerSocket.Stop()
    msg("Server Stopped")
    ButtonStart.Visibility = Windows.Visibility.Visible
    ButtonStop.Visibility = Windows.Visibility.Collapsed
    BW.CancelAsync()
    BWAccept.CancelAsync()
    StackPanelClient.Visibility = Windows.Visibility.Collapsed
    StackPanelServer.Visibility = Windows.Visibility.Collapsed
End Sub

End Class



Client:


VB
Imports System.Net.Sockets
Imports System.IO

Class MainWindow
Dim networkStream As NetworkStream

Private Sub ButtonStart_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonStart.Click
    Dim tcpClnt As New System.Net.Sockets.TcpClient
    Dim port As Integer = 8888
    Try
        tcpClnt.Connect(TextBoxServerIP.Text, port)
        networkStream = tcpClnt.GetStream()
    Catch ex As Exception
        MsgBox(ex.ToString())
    End Try
End Sub

Private Sub ButtonSend_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonSend.Click
    Dim fs As FileStream
    fs = New    FileStream("D:\Software\NIC\DCM\Series1\10.129.1125.111.1246.1101.20150106081616.1.dcm", FileMode.Open)
    Dim objReader As New BinaryReader(fs)
    Dim send() As Byte = objReader.ReadBytes(fs.Length)
    networkStream.Write(send, 0, send.Length)
    objReader.Close()
    fs.Close()
End Sub

Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    TextBoxServerIP.Text = "192.168.1.106"
End Sub
End Class


What I have tried:

The application works, but with an error. Suppose a file with the size of 1000 byte, in this code the buffer size is 16KB. The transferred file is 16KB not 1000 byte and some 0 is added to the end of file. What I must do for correction?
Posted
Updated 5-Apr-16 3:35am

1 solution

You are writing ClientSocket.ReceiveBufferSize bytes to the file here:
VB
FileStreamer.Write(bytesFrom, 0,  CInt(ClientSocket.ReceiveBufferSize))

even when you have received less bytes.

You must use the number of bytes that has been actually received instead which are returned by NetworkStream.Read():
VB
Dim numberOfBytesRead As Integer = 0
numberOfBytesRead = networkStream.Read(bytesFrom, 0, bytesFrom.Length)
'...
FileStreamer.Write(bytesFrom, 0,  numberOfBytesRead)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900