Page 1 of 2 12 LastLast
Results 1 to 40 of 44

Thread: [RESOLVED] [2005] .NET Sockets File Transfer Help

  1. #1

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Resolved [RESOLVED] [2005] .NET Sockets File Transfer Help

    I have created a program that uses tcp/ip sockets to communicate between the client and server. I am looking for a way to send a file to the server over this connection that already exists. I understand that a network stream will have to be used. I found this code on another post written by Atheist, that will send the contents of the file through the network stream. I think that will work.
    Code:
            Dim sendBuffer(1023) As Byte
            Dim fileToSend As String = "c:\somePicture.jpg"
            Dim fStream As System.IO.FileStream
            Dim bytesRead As Integer = 0
    
            If System.IO.File.Exists(fileToSend) Then
                fStream = New System.IO.FileStream(fileToSend, IO.FileMode.Open)
                Do
                    bytesRead = fStream.Read(sendBuffer, 0, 1024)
                    If bytesRead > 0 Then
                        nStream.Write(sendBuffer, 0, bytesRead) 'Where nStream is the NetworkStream for the connection
                    End If
                Loop While bytesRead > 0
            End If
    As for the part that im not sure of, is what do i have to do to recieve the file on the server side? Maybe somebody could supply come code for piecing the file back together. Another things that would be useful would be a list of procedure that needs to be followed to get the transfer to work. as of right now I have

    Client:
    1.get file path
    2.read file into pieces
    3.send each piece

    Server:
    4.read each piece
    5. assemble back into a file

    Thanks for the help. -Adam

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Does the receiving end know how large the file is in advance? Or to rephrase the question; What does the receiving end know about the file being transfered?

    And also, will you be using this connection for other communication whilst this data is being sent?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    The receiving(server) end will know nothing about the file in advance. This is for a robot project that I am working on. I need to be able to send the updated version of the control programs to it. There is a chance that it will be sending during other communication, I would like it to be able to do this but if it isnt possible, its not a major loss. -Adam

  4. #4
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Quote Originally Posted by adamj12b
    The receiving(server) end will know nothing about the file in advance. This is for a robot project that I am working on. I need to be able to send the updated version of the control programs to it. There is a chance that it will be sending during other communication, I would like it to be able to do this but if it isnt possible, its not a major loss. -Adam
    Well, I really think you should open up a new connection for the file transfer, then close it once it finishes. It will make things alot easier for you.
    You could then, before the transfer starts, tell the receiving end how large the file is (on the main tcp connection), so it knows how many bytes it should expect.
    I could try to throw together a class for you if you'd like, or would you rather try yourself?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  5. #5

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    So by creating a new connection I would still be able to control my robot and run query's, while sending the update files to it? Sounds good

    It would be very handy if you did create the class file, because im not a programing expert. I'm an electronics engineering student. lol

    In this class, would it be used in each project (Client and server) and access different parts of the class?

    The other thing I was wondering about is creating it so that it can show a progress bar for the file being sent. I think that this would be easy, by just comparing the total size of the file to the amount sent.

    Thanks for the help-Adam

  6. #6
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Alright I've thrown together this, I wouldnt call it 100% complete (needs improved error handling), but does its job.

    The way this works is; When host A wants to send a file to host B, host A creates an instance of the FileTransferSend class (and stores it in a collection of some sort, just to keep a reference to each transfer) and sends the following information to host B:
    -The name of the file.
    -The size of the file (in bytes)
    -The port on which host B should connect to receive the file.

    Once host B receives this information, it should create an instance of the FileTransferReceive class (and store it in a collection, as above), passes all the information it just received to the FileTransferReceive's constructor, along with the hosts address.
    The FileTransferReceive class will automatically connect to the given address and portnumber, and upon doing so, host A will automatically begin sending the file.

    That was a lousy explanation...well, if you just add these classes to your project(s), we can go through it step-by-step.

    Here are the two classes:
    VB.NET Code:
    1. Public Class FileTransferReceive
    2.     Private m_client As System.Net.Sockets.Socket
    3.     Private m_file As String
    4.     Private m_fileLength As Long
    5.     Private m_thread As System.Threading.Thread
    6.     Private BUFFER_SIZE As Integer = 8192
    7.  
    8.     Public Event TransferFinished(ByVal sender As FileTransferReceive, ByVal file As String)
    9.     Public Event TransferFailed(ByVal sender As FileTransferReceive, ByVal file As String)
    10.  
    11.     Sub New(ByVal address As System.Net.IPAddress, ByVal port As Integer, ByVal file As String, ByVal length As Long)
    12.         m_file = file
    13.         m_fileLength = length
    14.         m_client = New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
    15.         m_client.Connect(address, port)
    16.         m_thread = New System.Threading.Thread(AddressOf doRead)
    17.         m_thread.IsBackground = True
    18.         m_thread.Start()
    19.     End Sub
    20.  
    21.     Private Sub doRead()
    22.         Dim receiveBuffer(BUFFER_SIZE - 1) As Byte
    23.         Dim bytesRead As Integer = 0
    24.         Dim totalBytesRead As Long = 0
    25.         Dim fStream As System.IO.FileStream = Nothing
    26.         Dim failed As Boolean = False
    27.         Try
    28.             fStream = New System.IO.FileStream(System.IO.Path.Combine(Application.StartupPath, m_file), IO.FileMode.Create)
    29.  
    30.             Do
    31.                 bytesRead = m_client.Receive(receiveBuffer, BUFFER_SIZE, Net.Sockets.SocketFlags.None)
    32.                 If bytesRead > 0 Then
    33.                     fStream.Write(receiveBuffer, 0, bytesRead)
    34.                     totalBytesRead += bytesRead
    35.                 End If
    36.             Loop Until totalBytesRead = m_fileLength
    37.         Catch
    38.             failed = True
    39.         Finally
    40.             If Not fStream Is Nothing Then
    41.                 fStream.Close()
    42.             End If
    43.         End Try
    44.  
    45.         If failed Then
    46.             RaiseEvent TransferFailed(Me, m_file)
    47.         Else
    48.             RaiseEvent TransferFinished(Me, m_file)
    49.         End If
    50.  
    51.     End Sub
    52. End Class

    VB.NET Code:
    1. Public Class FileTransferSend
    2.     Private m_listener As System.Net.Sockets.Socket
    3.     Private m_Thread As System.Threading.Thread
    4.     Private m_file As String
    5.     Private m_port As Integer
    6.     Private Const BUFFER_SIZE As Integer = 8192
    7.  
    8.     Public Event TransferFinished(ByVal sender As FileTransferSend, ByVal file As String)
    9.     Public Event TransferFailed(ByVal sender As FileTransferSend, ByVal file As String)
    10.  
    11.     Sub New(ByVal file As String)
    12.         m_file = file
    13.  
    14.         m_listener = New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
    15.         m_listener.Bind(New System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)) 'Because we dont care what port we are assigned, we specify 0.
    16.         m_listener.Listen(1)
    17.  
    18.         m_Thread = New System.Threading.Thread(AddressOf doListen)
    19.         m_Thread.IsBackground = True
    20.         m_Thread.Start()
    21.  
    22.         m_port = DirectCast(m_listener.LocalEndPoint, System.Net.IPEndPoint).Port
    23.     End Sub
    24.  
    25.     Private Sub doListen()
    26.         Dim host As System.Net.Sockets.Socket
    27.         Dim bytesRead As Integer = 0
    28.         Dim sendBuffer(BUFFER_SIZE - 1) As Byte
    29.         Dim failed As Boolean = False
    30.         Dim fStream As System.IO.FileStream = Nothing
    31.  
    32.         host = m_listener.Accept()
    33.  
    34.         'Client is connected, so lets begin transfering the file.
    35.         If System.IO.File.Exists(m_file) Then
    36.             Try
    37.                 fStream = New System.IO.FileStream(m_file, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
    38.                 Do
    39.                     bytesRead = fStream.Read(sendBuffer, 0, BUFFER_SIZE)
    40.                     If (bytesRead > 0) Then
    41.                         host.Send(sendBuffer, bytesRead, Net.Sockets.SocketFlags.None)
    42.                     End If
    43.                 Loop While bytesRead > 0
    44.             Catch
    45.                 failed = True
    46.             Finally
    47.                 If Not fStream Is Nothing Then
    48.                     fStream.Close()
    49.                 End If
    50.             End Try
    51.         Else
    52.             failed = True
    53.             'TODO: Notify the host that the file doesnt exist.
    54.         End If
    55.  
    56.         If failed Then
    57.             RaiseEvent TransferFailed(Me, m_file)
    58.         Else
    59.             RaiseEvent TransferFinished(Me, m_file)
    60.         End If
    61.     End Sub
    62.  
    63.     Public ReadOnly Property GetPortNumber() As Integer
    64.         Get
    65.             Return m_port
    66.         End Get
    67.     End Property
    68. End Class
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  7. #7

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    WOW. Thankyou. I created 2 new projects just to figure out everything and make sure it works before putting it in my robot program. The projects are called FileTransferSend and FileTransferRecieve. I added the code to the one it belongs in. It looks good, just not sure where I put the address of the file I want to send and and what I call to start the Process.Again thankyou.-Adam

  8. #8
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Whenever you want to send a file you create a new FileTransferSend class instance, and pass the address to the file in the constructor:
    VB.NET Code:
    1. Dim transfer As New FileTransferSend("C:\somePicture.jpg")
    Directly after creating this instance, you should send the information to the reciever: Filename, filesize, and port number (retrieve the portnumber from by using the GetPortNumber property from the FileTransferSend instance you just created)
    This is so the receiver can create a FileTransferReceive class instance to receive your file.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  9. #9
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Quote Originally Posted by adamj12b
    ... and what I call to start the Process.Again thankyou.-Adam
    You can send as many files as you like, whenever you like. Just do the process all over again.

    Oh I should also tell you;
    You must add the classes to a collection of some sort after creating them, or else they'll be unreferenced and could be picked up for garbage collection. You also need to handle the TransferFailed/TransferFinished events in which you remove the instance that raised the event from the collection.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  10. #10

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    Im kinda confused. I can send the information about the file to the receiving end, but im not sure how I call the receive code with the information and start the receive process. Also, how dose it know where to save the file to? Thannk-you for your help. -Adam

  11. #11
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Alright, when you receive the information about the file on the receiving end, create a FileTransferReceive instance and pass the information to the constructor. The first argument of the constructor is the IP-address of the client, so retreiving the ip address of the sender kinda depends on how your application is designed.
    VB.NET Code:
    1. Dim transfer As New FileTransferReceive(SomeIP, PortNumber, FileName, FileSize)
    2. ' Add it to a collection of some sort, and add the eventhandlers for TransferFinished and TransferFailed.

    If you have the possibility to, posting your code would help me give you better examples of how you should go about doing this.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  12. #12
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Quote Originally Posted by adamj12b
    Also, how dose it know where to save the file to? Thannk-you for your help. -Adam
    Currently, all the files are statically set to be downloaded into the applications startup folder, right on this line:
    VB.NET Code:
    1. fStream = New System.IO.FileStream(System.IO.Path.Combine(Application.StartupPath, m_file), IO.FileMode.Create)
    You could change this to whatever you want, or even create a new parameter in the constructor and pass the directory through there.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  13. #13

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    Here are the 2 projects that I created to set this up and get working. The code in it is the same as what I used in my actual program. I then added the code you wrote. -Adam
    Attached Files Attached Files

  14. #14
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Alright, on the click eventhandler for the "Send file" button, you need to make some adjustments. It currently looks like this:
    VB.NET Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSendFile.Click
    2.         Dim transfer As New FileTransferSend("C:\Sent\RobotSettings.txt")
    3.  
    4.         Dim strHostName As String
    5.  
    6.         strHostName = System.Net.Dns.GetHostName()
    7.         send_to_robot(System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString(), m_port, "test.jpg", GetFileSize("C:\test.jpg"), "FLE#")
    8.  
    9.     End Sub

    First off you are trying to send "C:\Sent\RobotSettings.txt", but you're telling the receiver that he is receiving "test.jpg", this will give you a strange result.
    Furthermore you need to pass the port on which the receiver should connect to begin downloading the file. This port is returned from the transfer objects GetPortNumber property.
    But still even after fixing these minor things; your send_to_robot doesn't take that many arguments, you need to create a new subroutine for this or extend send_to_robot.

    VB.NET Code:
    1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSendFile.Click
    2.         Dim transfer As New FileTransferSend("C:\Sent\RobotSettings.txt")
    3.  
    4.         Dim strHostName As String
    5.  
    6.         strHostName = System.Net.Dns.GetHostName()
    7.         send_to_robot(System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString(), transfer.GetPortNumber, "RobotSettings.txt", GetFileSize("C:\Sent\RobotSettings.txt"), "FLE#")
    8.     End Sub
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  15. #15

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    Almost there. I was able to fix the problems on the sending side. All im having trouble with now is getting the ip address out of the message I send and into the start file receive statement.
    test Code:
    1. Private Function Start_File_Transfer(ByVal message As String) As Integer
    2.         Dim IPAddress, PortNumber, FileName, FileSize As String
    3.         Dim Comma1, Comma2, Comma3 As Integer
    4.  
    5.         Comma1 = InStr(message, ",")
    6.         Comma2 = InStr(Comma1 + 1, message, ",")
    7.         Comma3 = InStr(Comma2 + 1, message, ",")
    8.  
    9.         IPAddress = Mid(message, 1, Comma1 - 1)
    10.         PortNumber = Mid(message, Comma1 + 1, (Comma2 - Comma1) - 1)
    11.         FileName = Mid(message, Comma2 + 1, (Comma3 - Comma2) - 1)
    12.         FileSize = Mid(message, Comma3 + 1)
    13.  
    14.         'MsgBox(IPAddress & PortNumber & FileName & FileSize)
    15.  
    16.         Dim transfer As New FileTransferReceive(IPAddress, PortNumber, FileName, FileSize)
    17.         ' Add it to a collection of some sort, and add the eventhandlers for TransferFinished and TransferFailed.
    18.  
    19.     End Function

    The error Reads: Value of type 'String' cannot be converted to 'System.Net.IPAddress'. The ipaddress variable right after FileTransferRecieve( is what has the blue line under it.

    Thankyou for the help. Adam

  16. #16
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    You actually do not need to send the IP address to the receiver. If you have a socket for the connection to the sender (which you should), you can get its IP like this:
    VB.NET Code:
    1. Dim addr As System.Net.IPAddress = DirectCast(sock.RemoteEndPoint, System.Net.IPEndPoint).Address
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  17. #17

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    Awsome, Thankyou soo much for the help. I got it to work. The last 1 last thing that I am curious about. How would I display the progress of the file transfer in a progress bar? I tried adding the progressbar1.value = BytesRead code to the loop that sends the file, but it mess's up the transfer and only sends the first 8kb and stops, and also dosent increment the progress bar. I set the maximum value of the progress bar to the total amount of bytes of the file. Hope you can help me out with this . -Adam

  18. #18
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    It would be best to create a new event that we raise whenever the progress changes. Here, it would look something like this:

    VB.NET Code:
    1. Public Class FileTransferReceive
    2.     Private m_client As System.Net.Sockets.Socket
    3.     Private m_file As String
    4.     Private m_fileLength As Long
    5.     Private m_thread As System.Threading.Thread
    6.     Private BUFFER_SIZE As Integer = 8192
    7.  
    8.     Public Event TransferFinished(ByVal sender As FileTransferReceive, ByVal file As String)
    9.     Public Event TransferFailed(ByVal sender As FileTransferReceive, ByVal file As String)
    10.     Public Event TransferProgressChanged(ByVal sender As FileTransferReceive, ByVal current As Long, ByVal maximum As Long)
    11.  
    12.     Sub New(ByVal address As System.Net.IPAddress, ByVal port As Integer, ByVal file As String, ByVal length As Long)
    13.         m_file = file
    14.         m_fileLength = length
    15.         m_client = New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
    16.         m_client.Connect(address, port)
    17.         m_thread = New System.Threading.Thread(AddressOf doRead)
    18.         m_thread.IsBackground = True
    19.         m_thread.Start()
    20.     End Sub
    21.  
    22.     Private Sub doRead()
    23.         Dim receiveBuffer(BUFFER_SIZE - 1) As Byte
    24.         Dim bytesRead As Integer = 0
    25.         Dim totalBytesRead As Long = 0
    26.         Dim fStream As System.IO.FileStream = Nothing
    27.         Dim failed As Boolean = False
    28.         Try
    29.             fStream = New System.IO.FileStream(System.IO.Path.Combine(Application.StartupPath, m_file), IO.FileMode.Create)
    30.  
    31.             Do
    32.                 bytesRead = m_client.Receive(receiveBuffer, BUFFER_SIZE, Net.Sockets.SocketFlags.None)
    33.                 If bytesRead > 0 Then
    34.                     fStream.Write(receiveBuffer, 0, bytesRead)
    35.                     totalBytesRead += bytesRead
    36.                     RaiseEvent TransferProgressChanged(Me, totalBytesRead, m_fileLength)
    37.                 End If
    38.             Loop Until totalBytesRead = m_fileLength
    39.         Catch
    40.             failed = True
    41.         Finally
    42.             If Not fStream Is Nothing Then
    43.                 fStream.Close()
    44.             End If
    45.         End Try
    46.         If failed Then
    47.             RaiseEvent TransferFailed(Me, m_file)
    48.         Else
    49.             RaiseEvent TransferFinished(Me, m_file)
    50.         End If
    51.     End Sub
    52. End Class

    Note that you the download occurs on a separate thread, and since we are raising this event from the same thread, you can not access your forms controls directly from the eventhandler.

    By the way, are you adding the transfers to a collection after creating them?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  19. #19

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    I understand about the threading. I have a display delegate that I think will be able to handle changing the progress bar. I use it to add the data to list box from the sockets and serial port. As for the transfers to a collection, Im not sure what your talking about so im going to say no. lol. Also, I need to display the sent data on the sending side not the receiving side. One other thing, The raise events, how would you add code to them, so they execute it when that even happens? Like displaying a message when a transfer fails? I think thats it for now. Thank you for putting up with my ignorance. -Adam

  20. #20
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Quote Originally Posted by adamj12b
    I understand about the threading. I have a display delegate that I think will be able to handle changing the progress bar. I use it to add the data to list box from the sockets and serial port. As for the transfers to a collection, Im not sure what your talking about so im going to say no. lol.
    Hmm well lets ignore this part for a bit then, lets see if it works without it.
    Quote Originally Posted by adamj12b
    Also, I need to display the sent data on the sending side not the receiving side.
    Then just do the modifications i showed you in the FileTransferReceive in the FileTransferSend class instead
    Quote Originally Posted by adamj12b
    One other thing, The raise events, how would you add code to them, so they execute it when that even happens? Like displaying a message when a transfer fails?
    To add a handler for an event you use the AddHandler statement right after creating your FileTransferReceive/FileTransferSend class instance,
    VB.NET Code:
    1. AddHandler transfer.TransferFailed, AddressOf TransferFailedHandler
    2.  
    3. Private Sub TransferFailedHandler(ByVal sender As FileTransferReceive, ByVal file As String)
    4.     'sender is a reference to the transfer that failed.
    5.     'file is the name of the file that didnt download properly.
    6. End Sub
    In this case, TransferFailedHandler will be called everytime a TransferFailed event is raised. Just do the same on the other events, the only thing to keep in mind is that the eventhandlers signature must be identical with the events signature. In this case the signature is:
    (ByVal sender As FileTransferReceive, ByVal file As String)
    Quote Originally Posted by adamj12b
    I think thats it for now. Thank you for putting up with my ignorance. -Adam
    You're welcome.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  21. #21

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    OK, I added the differences to the send class, and only had a little bit of trouble. Heres the code and then I will describe.
    Send Class Code:
    1. Public Class FileTransferSend
    2.     Private m_listener As System.Net.Sockets.Socket
    3.     Private m_Thread As System.Threading.Thread
    4.     Private m_file As String
    5.     Private m_port As Integer
    6.     Private Const BUFFER_SIZE As Integer = 8192
    7.     Public Event TransferFinished(ByVal sender As FileTransferSend, ByVal file As String)
    8.     Public Event TransferFailed(ByVal sender As FileTransferSend, ByVal file As String)
    9.     Public Event TransferProgressChanged(ByVal sender As FileTransferSend, ByVal current As Long, ByVal maximum As Long) '**********
    10.  
    11.     Sub New(ByVal file As String)
    12.         m_file = file
    13.         m_listener = New System.Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
    14.         m_listener.Bind(New System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)) 'Because we dont care what port we are assigned, we specify 0.
    15.         m_listener.Listen(1)
    16.         m_Thread = New System.Threading.Thread(AddressOf doListen)
    17.         m_Thread.IsBackground = True
    18.         m_Thread.Start()
    19.         m_port = DirectCast(m_listener.LocalEndPoint, System.Net.IPEndPoint).Port
    20.     End Sub
    21.  
    22.     Private Sub doListen()
    23.         Dim host As System.Net.Sockets.Socket
    24.         Dim bytesRead As Integer = 0
    25.         Dim totalBytesRead As Long = 0 '**********
    26.         Dim sendBuffer(BUFFER_SIZE - 1) As Byte
    27.         Dim failed As Boolean = False
    28.         Dim fStream As System.IO.FileStream = Nothing
    29.  
    30.         host = m_listener.Accept()
    31.  
    32.         'Client is connected, so lets begin transfering the file.
    33.         If System.IO.File.Exists(m_file) Then
    34.             Try
    35.                 fStream = New System.IO.FileStream(m_file, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
    36.                 Do
    37.                     bytesRead = fStream.Read(sendBuffer, 0, BUFFER_SIZE)
    38.                     If (bytesRead > 0) Then
    39.                         host.Send(sendBuffer, bytesRead, Net.Sockets.SocketFlags.None)
    40.                         totalBytesRead += bytesRead '**********
    41.                         RaiseEvent TransferProgressChanged(Me, totalBytesRead, frmMain.GetFileSize(frmMain.OFD1.FileName)) '**********
    42.                     End If
    43.                 Loop While bytesRead > 0
    44.             Catch
    45.                 failed = True
    46.             Finally
    47.                 If Not fStream Is Nothing Then
    48.                     fStream.Close()
    49.                 End If
    50.             End Try
    51.         Else
    52.             failed = True
    53.             'TODO: Notify the host that the file doesnt exist.
    54.         End If
    55.         If failed Then
    56.             RaiseEvent TransferFailed(Me, m_file)
    57.         Else
    58.             RaiseEvent TransferFinished(Me, m_file)
    59.         End If
    60.     End Sub
    61.  
    62.     Public ReadOnly Property GetPortNumber() As Integer
    63.         Get
    64.             Return m_port
    65.         End Get
    66.     End Property
    67. End Class

    First off, All the lines that have '********** next to them are ones that I changed so that I could undo them if I need to. On this line:
    Line Code:
    1. RaiseEvent TransferProgressChanged(Me, totalBytesRead, frmMain.GetFileSize(frmMain.OFD1.FileName))
    I wasnt sure how to get the total size of the file into it, so I called the open dialog to get the file path and the get file size function. Is there something better I should use?

    Also, This is the code that dose it all.
    btnSendFile Code:
    1. Private Sub btnSendFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSendFile.Click
    2.         Dim strHostName, strIpAddress, strFilePath, strFileName As String '**********
    3.  
    4.         OFD1.ShowDialog() '**********
    5.         strFilePath = OFD1.FileName '**********
    6.         strFileName = OFD1.SafeFileName '**********
    7.  
    8.         Dim transfer As New FileTransferSend(strFilePath) '**********
    9.         AddHandler transfer.TransferFailed, AddressOf TransferFailedHandler '**********
    10.         AddHandler transfer.TransferProgressChanged, AddressOf TransferProgressChangedHandler '**********
    11.  
    12.         strHostName = System.Net.Dns.GetHostName() '**********
    13.         strIpAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString() '**********
    14.  
    15.         prgStatus.Maximum = GetFileSize(strFilePath) '**********
    16.  
    17.         send_to_robot(strIpAddress & "," & transfer.GetPortNumber & "," & strFileName & "," & GetFileSize(strFilePath), "FLE#") '**********
    18.     End Sub

    And the 2 subs for the handler's :
    Handlers Code:
    1. Private Sub TransferFailedHandler(ByVal sender As FileTransferSend, ByVal file As String) '**********
    2.         MsgBox("Oops...Something didnt work right.") '**********
    3.         'sender is a reference to the transfer that failed.'**********
    4.         'file is the name of the file that didnt download properly.'**********
    5.     End Sub '**********
    6.  
    7.     Private Sub TransferProgressChangedHandler(ByVal sender As FileTransferSend, ByVal file As String) '**********
    8.         DisplayMessage("PRG#" & "100")
    9.         'sender is a reference to the transfer that failed.'**********
    10.         'file is the name of the file that didnt download properly.'**********
    11.     End Sub '**********

    OK, On this line:
    Code:
            AddHandler transfer.TransferProgressChanged, AddressOf TransferProgressChangedHandler '**********
    underneath the "AddressOf TransferProgressChangedHandler" I get this error message:
    Error 1 Method 'Private Sub TransferProgressChangedHandler(sender As FileTransfer.FileTransferSend, file As String)' does not have the same signature as delegate 'Delegate Sub TransferProgressChangedEventHandler(sender As FileTransferSend, current As Long, maximum As Long)'. F:\Visual Basic\FileTransferSend\FileTransferSend\frmMain.vb 215 64 FileTransferSend
    Not too sure what that means. Hopefully you can let me kno if everything looks good also. Thanks. -Adam

    P.S. How do you get your vb code come up all colored and nice looking?

  22. #22
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    That error is caused by the fact that the TransferProgressChanged event has this signature:
    (ByVal sender As FileTransferReceive, ByVal current As Long, ByVal maximum As Long)
    And you're trying to add an eventhandler to it that looks like this:
    VB.NET Code:
    1. Private Sub TransferProgressChangedHandler(ByVal sender As FileTransferSend, ByVal file As String) '**********
    2.         DisplayMessage("PRG#" & "100")
    3.         'sender is a reference to the transfer that failed.'**********
    4.         'file is the name of the file that didnt download properly.'**********
    5.     End Sub '**********

    It needs to look like this:
    VB.NET Code:
    1. Private Sub TransferProgressChangedHandler(ByVal sender As FileTransferReceive, ByVal current As Long, ByVal maximum As Long) '**********
    2.         DisplayMessage("PRG#" & "100")
    3.         'sender is a reference to the transfer that failed.'**********
    4.         'file is the name of the file that didnt download properly.'**********
    5.     End Sub '**********

    About making the code colored, you have to specify that it is VB.NET code you're highlighting by wrapping it in:

    [HIGHLIGHT=VB.NET]

    Code goes here

    [/HIGHLIGHT]
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  23. #23

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    Cool, That fixed all the errors, but it dosent work anymore either lol. For some reason whenever I send a file it only sends the first 8kb which would be 1 full buffer, then it calls the transfer failed handler,(which at least I know that that works) then it shows my message box that says that something is wrong. since there are no errors im not sure where to go. I tried to put a break point thinking the the raise even that changes the progress bar might be causing the loop that sends the data to only run once, but the progress bar never changes and TransferProgressChangedHandeler never even gets called. The break was never reached. Im attaching both projects in there newest forms. -Adam
    Attached Files Attached Files

  24. #24
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    I believe its due to the fact that you're calling frmMain.GetFileSize(frmMain.OFD1.FileName) upon raising the event:
    VB.NET Code:
    1. RaiseEvent TransferProgressChanged(Me, totalBytesRead, frmMain.GetFileSize(frmMain.OFD1.FileName))
    m_file contains the path to the file, you should fetch the size of the file once, before you start sending:
    VB.NET Code:
    1. Dim fileLength As Long = New System.IO.FileInfo(m_file).Length
    Then use this fileLength variable instead of the GetFileSize call when raising the event.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  25. #25

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    I tried putting that in a few different places with no success. The same thing as before keeps happening. If I try to put that line in the form class it says m_file is not declared, and the only place that it dosent say that is inside the class file. It dosent make any since to me because the place that needs the file length info is inside the form class under that send file button. -Adam

  26. #26
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    Quote Originally Posted by adamj12b
    ...It dosent make any since to me because the place that needs the file length info is inside the form class under that send file button. -Adam
    Yes you need the file length there too.
    Try this: (only posting the DoListen sub)
    VB.NET Code:
    1. Private Sub doListen()
    2.         Dim host As System.Net.Sockets.Socket
    3.         Dim bytesRead As Integer = 0
    4.         Dim totalBytesRead As Long = 0 '**********
    5.         Dim sendBuffer(BUFFER_SIZE - 1) As Byte
    6.         Dim failed As Boolean = False
    7.         Dim fileLength As Long
    8.         Dim fStream As System.IO.FileStream = Nothing
    9.  
    10.         host = m_listener.Accept()
    11.  
    12.         'Client is connected, so lets begin transfering the file.
    13.         If System.IO.File.Exists(m_file) Then
    14.             Try
    15.                 fStream = New System.IO.FileStream(m_file, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
    16.                 fileLength = fStream.Length
    17.                 Do
    18.                     bytesRead = fStream.Read(sendBuffer, 0, BUFFER_SIZE)
    19.                     If (bytesRead > 0) Then
    20.                         host.Send(sendBuffer, bytesRead, Net.Sockets.SocketFlags.None)
    21.                         totalBytesRead += bytesRead '**********
    22.                         RaiseEvent TransferProgressChanged(Me, totalBytesRead, fileLength) '**********
    23.                     End If
    24.                 Loop While bytesRead > 0
    25.             Catch
    26.                 failed = True
    27.             Finally
    28.                 If Not fStream Is Nothing Then
    29.                     fStream.Close()
    30.                 End If
    31.             End Try
    32.         Else
    33.             failed = True
    34.             'TODO: Notify the host that the file doesnt exist.
    35.         End If
    36.         If failed Then
    37.             RaiseEvent TransferFailed(Me, m_file)
    38.         Else
    39.             RaiseEvent TransferFinished(Me, m_file)
    40.         End If
    41.     End Sub
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  27. #27

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [2005] .NET Sockets File Transfer Help

    Awesome, Thanks for all the help. I really appreciate it. -Adam

  28. #28
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [2005] .NET Sockets File Transfer Help

    So its all working for you now?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  29. #29

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Yep everything works great. The progress bar progresses as the file is transfered and I added code to the finished and failed handlers on the send side, because that is the only place that they are needed because the receive side dosent even have a monitor. The display delegate that I had worked fine for changing the value of the progress bar. The only thing that im not too sure of is what will happen if I try to add a message to the list box with the delegate while sending a file with the bar updating. maybe there is a better way to change the bar without using that delegate. Not the biggest deal though. Again thanks. -Adam

  30. #30
    Hyperactive Member Skatebone's Avatar
    Join Date
    Jan 2009
    Location
    Malta
    Posts
    279

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Very interesting thread

    Can u please attach the basic final code plz cause i didn't manage myself to arrange everything :/

    I have a situation Client and server. Server grabs screenshot, sends it to client very quickly, client opens it. Its like remote computer control tnx
    Life runs on code

  31. #31

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Sounds cool. I will try to dig up the code, but it might take me a day or 2.

    -Adam

  32. #32
    Hyperactive Member Skatebone's Avatar
    Join Date
    Jan 2009
    Location
    Malta
    Posts
    279

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Thanks alot king
    I really appreciate :P
    No need to dig though i can edit myself
    Just need to sort out the basics :P
    Life runs on code

  33. #33
    Addicted Member
    Join Date
    Feb 2007
    Location
    Netherlands
    Posts
    203

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Hey,

    Can you upload your final source code? Im realy interested in it.
    Last edited by thijsd; Nov 6th, 2018 at 11:49 AM.

  34. #34

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    What version of vb are you running?

    -Adam

  35. #35
    Addicted Member
    Join Date
    Feb 2007
    Location
    Netherlands
    Posts
    203

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Quote Originally Posted by adamj12b
    What version of vb are you running?

    -Adam
    2008

    ThijsD

  36. #36

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Hey Guys.

    Here you go. This should get you going. I hope it helps

    -Adam

    http://web.me.com/adamj12b/Directory...3_Entry_1.html

  37. #37
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Ah yes this project, I'm considering submitting these classes to the codebank. If you come across anything that needs change or fixing, please do tell.
    One thing it looks like I've failed to mention is just to be careful not handle the TransferProgressChanged event and do too much work in its eventhandler, as it'll be invoked on the same thread that transfers the file, it'll basically halt the transfer for as long as the eventhandler takes to execute.
    If you need to perform alot of work in the eventhandler, a solution is to directly invoke a method on the UI thread (using Me.Invoke in the eventhandler), and perform the work there instead.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  38. #38

    Thread Starter
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Hey Atheist,

    The only thing i can come up with is some way to include the send and receive class all together. I tried doing this before but it broke the code.

    -Adam

  39. #39
    Hyperactive Member Skatebone's Avatar
    Join Date
    Jan 2009
    Location
    Malta
    Posts
    279

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Thanks adam
    Life runs on code

  40. #40
    New Member
    Join Date
    Jan 2010
    Posts
    5

    Re: [RESOLVED] [2005] .NET Sockets File Transfer Help

    Hi Adam,

    I'm working on similar project and your project is really really helpful, because i'm a starter and dnt know much about programming..is there any way i can modify the program to run both the server and client on single machine (one Computer)? like using localhost (127.0.0.1)..please i need your help asap..i have tried running both server and client on my computer but it does not establish connection between the server and the client..cheers man, thnx for helping.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width