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

Thread: Client/Server Socket classes for file transfer

  1. #1

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Client/Server Socket classes for file transfer

    Here are two classes that can be used for client server applications:
    a listener class for the server and a tcpConnection class for the client which the listener also creates dynamically as connection requests arrive.

    These classes do most operations asnychronously in seperate threads, so in VB 2005 you have to either
    VB Code:
    1. CheckForIllegalCrossThreadCalls = False
    or handle cross-thread calls properly.

    Included are some nice methods for transferring files and large data blocks.

    clsListener
    Constructor:
    Private WithEvents listener As clsListener
    listener = New clsListener(PORT_NUM, optional DataBlockSize))
    Methods: Send messages to all connected clients
    Broadcast(msgTag) - Sends a 1-byte message
    Broadcast(msgTag, strX) - Sends a message string
    Broadcast(msgTag, byteData()) - Sends array of Byte data
    Events:
    ConnectionRequest(Requestor, AllowConnection) - Raised when a new connection request is made.
    Set AllowConnection to True to accept connection, otherwise connection is denied.
    Disconnect(Client) - A client has disconnected.
    MessageReceived(Client, msgTag)
    StringReceived(Client, msgTag, StrMessage) - Data is in a String
    DataReceived(Client, msgTag, memStream) - Data is in a memoryStream
    MsgTag is a 1-byte message identifier defined by end user
    tcpConnection
    Constructor:
    From Client:
    Private WithEvents client As tcpConnection
    client = New tcpConnection("localhost", PORT_NUM)
    From Server:
    clsListener handles this
    Methods: MsgTag is a 1-byte message identifier defined by end user
    Send(msgTag) - sends only the user-defined message tag
    Send(msgTag, strX) - sends a string
    Send(msgTag, byteData()) - sends an array of bytes
    SendFile(msgTag, FilePath) - Sends the contents of the file located at FilePath
    Events:
    Connect(ByVal sender As tcpConnection)
    Disconnect(ByVal Sender As tcpConnection)
    Data Reception: MsgTag is a 1-byte message identifier defined by end user
    MessageReceived(Sender, msgTag)
    StringReceived(Sender, msgTag, StrMessage) - Data is in a String
    DataReceived(Sender, msgTag, memStream) - Data is in a memoryStream
    TransferProgress(Sender, msgTag, Percentage) - Periodically notifies end user of what percentage of data
    has been transfered for bytedata and file transfers
    Examples of Use:
    Server Side
    The Listener starts to listen when the class is instantiated
    VB Code:
    1. Private WithEvents listener As clsListener
    2. listener = New clsListener(PORT_NUM, PACKET_SIZE)
    When a connection request comes in we have to decided whether to accept it or not.
    VB Code:
    1. Private Sub listener_ConnectionRequest(ByVal requestor As System.Net.Sockets.TcpClient, _
    2.         ByRef AllowConnection As Boolean) Handles listener.ConnectionRequest
    3.         'Here you can examine the requestor to determine whether to accept the connection or not
    4.         Debug.Print("Connection Request")
    5.         AllowConnection = True
    6.     End Sub
    Now we have to decide how we want to respond to client requests. Here is an example of responding to a string sent from the client by sending back the file identified in the string.
    VB Code:
    1. Private Sub listener_StringReceived(ByVal Sender As tcpConnection, ByVal msgTag As Byte, _
    2.         ByVal message As String) Handles listener.StringReceived
    3.         'This is where the client will send us requests for file data using our
    4.         ' predefined message tags
    5.         Debug.Print("String Received from Client: " & message)
    6.         Select Case msgTag
    7.             Case Requests.PictureFile
    8.                 Sender.SendFile(msgTag, picDir & message)
    9.             Case Requests.DataFile
    10.                 Sender.SendFile(msgTag, fileDir & message)
    11.         End Select
    12.     End Sub
    Client Side
    Connect to our server
    VB Code:
    1. Private WithEvents client As tcpConnection
    2.     Private Sub cmdConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    3.         Handles cmdConnect.Click
    4.         Try
    5.             client = New tcpConnection(txtServer.Text, PORT_NUM)
    6.         Catch ex As Exception
    7.             MessageBox.Show(Me, ex.Message, "Network Error", MessageBoxButtons.OK, _
    8.                 MessageBoxIcon.Error)
    9.             Me.Dispose()
    10.         End Try
    11.     End Sub
    Our server is set up to accept requests for picture and data files. Request a Picture vbcode]client.Send(Requests.PictureFile, "bliss.bmp")[/Highlight]Request a file
    VB Code:
    1. client.Send(Requests.DataFile, "wg_cs_1.mpg")
    The responses will come here. When they come in put the picture into our local picturebox control and save the file to the local disk.
    VB Code:
    1. Private Sub client_DataReceived(ByVal Sender As tcpConnection, ByVal msgTag As Byte, _
    2.         ByVal mstream As System.IO.MemoryStream) Handles client.DataReceived
    3.         'This code is run in a seperate thread from the thread that started the form
    4.         'so we must either handle any control access in a special thread-safe way
    5.         'or ignore illegal cross thread calls
    6.         Select Case msgTag
    7.             Case Requests.PictureFile
    8.                 'picture data, put into our local picturebox control
    9.                 'use a thread-safe manner for this action
    10.                 SetPicture(mstream)
    11.             Case Requests.DataFile
    12.                 'file data, save to a local file
    13.                 SaveFile("C:\new.mpg", mstream)
    14.         End Select
    15.     End Sub
    16.  
    17. #Region "How to properly handle cross thread calls instead of ignoring them"
    18.     Delegate Sub SetPictureCallback(ByVal mstream As System.IO.MemoryStream)
    19.  
    20.     Private Sub SetPicture(ByVal mstream As System.IO.MemoryStream)
    21.         ' Thread-safe way to access the picturebox
    22.         ' This isn't really needed because we are ignoring illegal cross thread calls.
    23.         If Me.PictureBox1.InvokeRequired Then
    24.             Dim d As New SetPictureCallback(AddressOf SetPicture)
    25.             Me.Invoke(d, New Object() {mstream})
    26.         Else
    27.             PictureBox1.Image = Image.FromStream(mstream)
    28.         End If
    29.     End Sub
    30. #End Region
    31.  
    32.     Private Sub SaveFile(ByVal FilePath As String, ByVal mstream As System.IO.MemoryStream)
    33.         'save file to path specified
    34.         Dim FS As New FileStream(FilePath, IO.FileMode.Create, IO.FileAccess.Write)
    35.         mstream.WriteTo(FS)
    36.         mstream.Flush()
    37.         FS.Close()
    38.     End Sub

    Attached are the full projects

    Changes:
    Fixed bug that prevented more than one client from connecting to server.
    Fixed problem with percent data transferred number.
    Added data block size parameter to Listener class constructor.
    Attached Files Attached Files
    Last edited by moeur; Mar 5th, 2006 at 01:34 PM.

  2. #2

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    If you try out this code and find a problem then let me know.
    Also any suggestions for additions to the code?
    Last edited by moeur; Mar 3rd, 2006 at 07:56 PM.

  3. #3
    Junior Member
    Join Date
    Aug 2005
    Posts
    30

    Re: Client/Server Socket classes for file transfer

    can u please upload whole project of transferring file... i need it to learn

  4. #4

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    OK, I've uploaded a client and Server app.

  5. #5
    Junior Member
    Join Date
    Aug 2005
    Posts
    30

    Re: Client/Server Socket classes for file transfer

    Quote Originally Posted by moeur
    OK, I've uploaded a client and Server app.
    hey man thanks but still having poblem i am using vb.net 2003 while i think u made it in upper version so i am getting error message that this form is made on higher version of visual studio... any suggestion which will help me to run this program or is it i have to install 2005

  6. #6

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    Are you getting the error when you try to load the two classes into a 2003 project that you build also?

  7. #7
    Junior Member
    Join Date
    Aug 2005
    Posts
    30

    Re: Client/Server Socket classes for file transfer

    Quote Originally Posted by moeur
    Are you getting the error when you try to load the two classes into a 2003 project that you build also?


    dude i dint get u what u asking ........... but if u mean that do i get error when i load any of other project in 2003.... than no i dont get error but when i am loading ur project i am getting error as i had mentioned above.
    can u please tell me which version of .net u had used.

  8. #8

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    The project was developed in 2005, but you should be able to load the clsListener.vb and tcpConnection.vb files into a new project in 2003. Then in your form just enter the code I show above.

    Does that not work?

  9. #9
    Junior Member
    Join Date
    Aug 2005
    Posts
    30

    Re: Client/Server Socket classes for file transfer

    Quote Originally Posted by moeur
    The project was developed in 2005, but you should be able to load the clsListener.vb and tcpConnection.vb files into a new project in 2003. Then in your form just enter the code I show above.

    Does that not work?
    will try and let u know thanks dude....... or atlast will find for 2005 cd and install it and work ur program der

  10. #10
    Frenzied Member Inuyasha1782's Avatar
    Join Date
    May 2005
    Location
    California, USA
    Posts
    1,035

    Re: Client/Server Socket classes for file transfer

    Is it possible to actually send data with the client side? Like not a request, just raw data, like sending an HTTP Request to a webserver.
    Age - 15 ::: Level - Advanced
    If you find my post useful please ::Rate It::


  11. #11

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    I don't understand the question.

    If you have a connection with a server then the client can send data.

  12. #12
    Frenzied Member Inuyasha1782's Avatar
    Join Date
    May 2005
    Location
    California, USA
    Posts
    1,035

    Re: Client/Server Socket classes for file transfer

    You show code like this:

    Code:
    client.Send(Requests.DataFile, "wg_cs_1.mpg")
    That requests a data file from the server, and tells it the file it wants. Well, I don't want to request a file, I just want to send a command to the server, how do I do that?
    Age - 15 ::: Level - Advanced
    If you find my post useful please ::Rate It::


  13. #13

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    These two classes are for building your own client/server programs.

    I think what you are saying is that you want to send data to a server that you have not written.

    If that is the case then I would not use either of these classes, but instead use the tcpClient class that comes with .NET.

  14. #14
    New Member
    Join Date
    Apr 2006
    Posts
    5

    Re: Client/Server Socket classes for file transfer

    Okay, I'm having a major foobar here. Everything works great but how do I make the server disconnect the client when I want it to? Or Vice Versa.
    Last edited by seanwill2; Apr 25th, 2006 at 09:45 AM.

  15. #15
    New Member
    Join Date
    Jun 2006
    Posts
    1

    Re: Client/Server Socket classes for file transfer

    Hey,

    Thanks for all your effect in this moeur, Impressive easy to use bit off code.

    What i am interested in is adding a user/password authentication between the client and server do you have any idea how this could be done. I have looked everywhere but cant find anything unless i am looking in the wrong places.

    Thanks Chris

  16. #16
    New Member
    Join Date
    Jun 2006
    Posts
    1

    Re: Client/Server Socket classes for file transfer

    Hi,
    Thanks for the great work.
    But i need to know how to disconnect programtically the client from the server.

  17. #17
    Member
    Join Date
    Jul 2006
    Posts
    40

    Re: Client/Server Socket classes for file transfer

    Correct me if I am wrong, but there is a method on the client side. Method is called "client_Disconnect" which handles "client.disconnect"

    you can either call the method above or create a method or a button which can handle client.disconnect event.

    Hope that helps.

  18. #18
    New Member
    Join Date
    Sep 2006
    Posts
    6

    Re: Client/Server Socket classes for file transfer

    Error! Messages get joined. To use Zero length EndReceive Reply to devide one message from another is wrong because if you send one message after another in multi-thread app and if client and server on the same PC you don't have Zero length EndReceive Reply betwin messages. So some messages get lost.
    Solution! You need to implement message length field and parse In Buffer which will be appended when new data received.

  19. #19
    New Member
    Join Date
    Sep 2006
    Posts
    6

    Re: Client/Server Socket classes for file transfer

    oops! it IS implemented, but doesn't work in described conditions.
    I replaced original "Case RequestTags.DataTransfer" in "tcpConnection.ReadOneByte" with following:
    VB Code:
    1. Case RequestTags.DataTransfer
    2.                 'a block of data is coming
    3.                 'Format of this transaction is
    4.                 '   DataTransfer identifier byte
    5.                 '   Pass-Through Byte contains user defined data
    6.                 '   Length of data block (max size = 2,147,483,647 bytes)
    7.                 SyncLock client.GetStream
    8.                     r = New BinaryReader(client.GetStream)
    9.                     'next we expect a pass-through byte
    10.                     passThroughByte = r.ReadByte
    11.                     'next expect length of data (Int32)
    12.                     lenData = r.ReadInt32
    13.                     'now comes the data, save it in a memory stream
    14.                     mStream = New MemoryStream()
    15.                     mStream.Write(r.ReadBytes(lenData), 0, lenData)
    16.                     mStream.Capacity = lenData
    17.                     'Continue the asynchronous read from the NetworkStream
    18.                     Me.client.GetStream.BeginRead(readByte, 0, 1, AddressOf ReceiveOneByte, Nothing)
    19.                 End SyncLock
    20.                 'once all data has arrived, pass it on to the end user as a stream
    21.                 RaiseEvent DataReceived(Me, passThroughByte, mStream)
    22.                 mStream.Dispose()
    It solved My Issue. Any ideas if this code may raise any other issues i missed.
    Last edited by mityVB2005; Oct 14th, 2006 at 09:42 AM.

  20. #20
    New Member
    Join Date
    Sep 2006
    Posts
    6

    Re: Client/Server Socket classes for file transfer

    Another Issue is that u get error if you are Broadcasting and at that moment one of the clients get closed. You get collection modified exception.

  21. #21
    New Member
    Join Date
    Oct 2006
    Location
    Belgium
    Posts
    5

    Re: Client/Server Socket classes for file transfer

    Hi all,

    I have a related question, but not an issue or so.
    I tried the code and it seems to work fine.
    But I added some kind of log datagrid.
    But when I try to access the datagrid in the listener_ConnectionRequest sub of the server form, I get a cross-thread exception.
    Is there any way I can access that control from that sub?

    Thanx,

    Sacha

  22. #22

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    see post #1 for cross-thread answer

  23. #23
    New Member
    Join Date
    Oct 2006
    Location
    Belgium
    Posts
    5

    Re: Client/Server Socket classes for file transfer

    Must have overlooked it .
    I've looked at the sub to set the image of the picturebox,
    but I can't get it to work some way with my datagrid.

    The delegate sub and setpicture sub using invokerequired etc is all new to me.
    What I actually want, is adding a row to a datagrid.

    I have a sub:

    VB Code:
    1. Private Sub writeOutput()
    2.  
    3.         Dim row As New DataGridViewRow
    4.         row.Height = 16
    5.  
    6.         ' all code for adding cells to the row
    7.         ' after that, it should add the row to the datagrid
    8.  
    9.         dgOutput.Rows.Add(row) ' dgOutput is the datagrid I can`t access
    10.         row.Dispose()
    11.         row = Nothing
    12.                
    13. End Sub

    this sub writeOutput() is called in the listener_ConnectionRequest sub.
    Any help would be appreciated .

    Thank you.
    Last edited by sachavdk; Oct 27th, 2006 at 11:05 AM.

  24. #24
    New Member
    Join Date
    Sep 2006
    Posts
    6

    Re: Client/Server Socket classes for file transfer

    This block of code gives errors!
    selected string raises errors when socket is not connected.
    VB Code:
    1. [U][I][B] SyncLock client.GetStream[/B][/I][/U]
    2.             'if error occurs here then socket has closed
    3.             Try
    4.                 client.GetStream.EndRead(ar)
    5.             Catch
    6.                 RaiseEvent Disconnect(Me)
    7.                 Exit Sub
    8.             End Try
    9.         End SyncLock

    I guess u need to change this block to:

    VB Code:
    1. Try
    2.             SyncLock client.GetStream
    3.                 'if error occurs here then socket has closed
    4.                 client.GetStream.EndRead(ar)
    5.             End SyncLock
    6.         Catch
    7.             RaiseEvent Disconnect(Me)
    8.             Exit Sub
    9.         End Try
    Last edited by mityVB2005; Oct 30th, 2006 at 06:25 AM.

  25. #25
    New Member
    Join Date
    Sep 2006
    Posts
    6

    Re: Client/Server Socket classes for file transfer

    To sachavdk

    VB Code:
    1. Private Delegate Sub DGwriteOutput()
    2.  
    3. Private Sub listener_ConnectionRequest(...) Handles ...
    4. ....
    5. dgOutput.Invoke(new DGwriteOutput(AddressOf writeOutput))
    6. .....
    7. End Sub
    8.  
    9. Private Sub writeOutput()
    10.  
    11.         Dim row As New DataGridViewRow
    12.         row.Height = 16
    13.  
    14.         ' all code for adding cells to the row
    15.         ' after that, it should add the row to the datagrid
    16.  
    17.         dgOutput.Rows.Add(row) ' dgOutput is the datagrid I can`t access
    18.         row.Dispose()
    19.         row = Nothing
    20.                
    21. End Sub

  26. #26
    Member
    Join Date
    Nov 2005
    Posts
    57

    Re: Client/Server Socket classes for file transfer

    Thank you to Moeur for a great bit of code, but I am still confused on one aspect of it. When either the server or a client loses connection, I am not sure how to handle it. As it is, my program instantly crashes on the client end if I exit the program on the server end, for example.

  27. #27

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    I'm sorry, but I don't have much time to look into this problem for you. Did you try making the change suggested in post #24?

  28. #28
    New Member
    Join Date
    Jan 2008
    Posts
    1

    Angry Re: Client/Server Socket classes for file transfer

    After I run the SaveFile routine, I am getting a Permissions Denied error when trying to update the original file and when I rename and move the original file. Is there any code to run to disconnect from the original file once it has been saved in it's new spot?

  29. #29
    Addicted Member
    Join Date
    Mar 2007
    Posts
    200

    Re: Client/Server Socket classes for file transfer

    Excuse me, I'm very Dependant on and thankful for this class noeur.
    And though I'm still amaturish, i think i found a BUG.(edit: wait, the guy above already noticed it ><)

    It has something to do with file transfer. After the class reads from a certain file and writes it into the stream, the class/process is still attached to the file in someway. (i don't think the reader is closed properly) so when i try to modify/delete/open THAT file after the 'reading' a exception is thrown.

  30. #30

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    In the code for the tcpConnection.SendFile method, Add the following line

    Code:
                Loop While byteArray.Length = PACKET_SIZE
                'make sure all data is sent
                w.Flush()
                w.Close() '<=== Add this line
            End SyncLock
        End Sub
    #End Region

  31. #31
    Addicted Member
    Join Date
    Mar 2007
    Posts
    200

    Re: Client/Server Socket classes for file transfer

    Thanks for the reply. But yes i have tried that before, and theres another problem with that. If you close it there, then when u try to send the file next time, the writer would still be closed, hence another exception.

    A friend gave me the advice to close the readers or whatever in instead, so for future reference add,

    So:
    fs.close()
    r.close()

  32. #32
    Addicted Member
    Join Date
    Mar 2007
    Posts
    200

    Re: Client/Server Socket classes for file transfer

    nvm (delete this post)?
    Last edited by Zapper; Jun 22nd, 2008 at 10:53 PM.

  33. #33
    New Member
    Join Date
    Jun 2008
    Posts
    3

    Re: Client/Server Socket classes for file transfer

    Hi, I send and received data, all work OK when I send / received file alone. But when I tried to sent / received file with loop, program stopped. Question, how can I check when latest event (send or received) is done?

  34. #34
    Addicted Member
    Join Date
    Mar 2007
    Posts
    200

    Re: Client/Server Socket classes for file transfer

    Hi Mik! Welcome to the forums!

    Well first, can you either tell us what you mean by receiving a file with loop or show post up some code you have written?

  35. #35
    New Member
    Join Date
    Jun 2008
    Posts
    3

    Re: Client/Server Socket classes for file transfer

    Hi

    I mean loop, if I have 10 picture names in listbox and I send all pictures of the list with loop.

    same is possible for...next statement, example:

    Private Sub cmdGetFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles cmdGetFile.Click
    Dim x As Integer
    'request a file from server
    ' Example getting pictures
    RecPathFile = "C:\Users\Dan\Pictures\"
    For x = 1 To 5
    client.Send(Requests.DataFile, RecPathFile & x & ".jpg")
    ' How can I test when last action is finnish?

    ' While action finnished

    ' End While
    Next

    End Sub

  36. #36
    Addicted Member
    Join Date
    Mar 2007
    Posts
    200

    Re: Client/Server Socket classes for file transfer

    (edit) wait it was asynchronous,
    I think there is a Check for "Progress" Routine in his class?

    What was the error by the way?

  37. #37
    New Member
    Join Date
    Jun 2008
    Posts
    3

    Re: Client/Server Socket classes for file transfer

    How can I chech "Progress" Routine?

    No errors, the server program only crash and Client jam and
    when I Debug all is OK because step by step debug still program run time.

    I write two seconds "pause" routine before send routine and all work OK, but I don't know what happen when used very slow network connection.

    that's why I want use the check routine

  38. #38

    Thread Starter
    Old Member moeur's Avatar
    Join Date
    Nov 2004
    Location
    Wait'n for Free Stuff
    Posts
    2,712

    Re: Client/Server Socket classes for file transfer

    This class can really only handle one file at a time. Therefore this is how I would handle transferring your five files. Add these two line at the form level
    Code:
        Private FileNumber As Integer = 1
        Private Const LastFile As Integer = 5
    Then, to start the transfer begin with the first file
    Code:
        Private Sub cmdGetFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
            Handles cmdGetFile.Click
            'request 1st file from server
            client.Send(Requests.DataFile, String.Format("RecPathFile{0}.jpg", FileNumber))
        End Sub
    Finally, when the file has finished transferring automatically begin transfer of the next. Keep doing this until all files have been transferred.
    Code:
        Private Sub client_DataReceived(ByVal Sender As tcpConnection, ByVal msgTag As Byte, _
            ByVal mstream As System.IO.MemoryStream) Handles client.DataReceived
            Select Case msgTag
                Case Requests.DataFile
                    'save file data to a local file
                    SaveFile(String.Format("RecPathFile{0}.jpg", FileNumber), mstream)
                    'increment file number
                    FileNumber += 1
                    'request next file
                    If FileNumber <= LastFile Then
                        client.Send(Requests.DataFile, String.Format("RecPathFile{0}.jpg", FileNumber))
                    Else
                        MsgBox("All files have been transferred")
                    End If
            End Select
        End Sub
    I haven't tested this so you might have to debug a step or two, but I think it should work.

  39. #39
    Addicted Member
    Join Date
    Mar 2007
    Posts
    200

    Re: Client/Server Socket classes for file transfer

    I struggled to modify the sendfile() to a sendimage() function in the tcpConnectionClass. But i managed somehow, tested and working:

    vb Code:
    1. Public Sub SendImage(ByVal msgTag As Byte, ByVal Image As Bitmap)
    2.         'max filesize is 2GB
    3.         Dim ms As New MemoryStream
    4.         'Converts the image into a memory stream
    5.         Image.Save(ms, Imaging.ImageFormat.Jpeg)
    6.  
    7.         SyncLock client.GetStream
    8.             Dim w As New BinaryWriter(client.GetStream)
    9.             'notify that image data is coming
    10.             w.Write(RequestTags.DataTransfer)
    11.             'send user-define message byte
    12.             w.Write(msgTag)
    13.             'send size of image
    14.             w.Write(CInt(ms.Length))
    15.  
    16.             'Converts memory stream into an array of bytes to be sent
    17.             Dim byteArray() As Byte = ms.GetBuffer()
    18.             'Send the image data
    19.             For i As Long = 0 To ms.Length Step PACKET_SIZE
    20.                 If ms.Length - i >= PACKET_SIZE Then
    21.                     w.Write(byteArray, CInt(i), PACKET_SIZE)
    22.                 Else
    23.                     w.Write(byteArray, CInt(i), CInt(ms.Length - i))
    24.                 End If
    25.             Next
    26.             'make sure all data is sent
    27.             w.Flush()
    28.         End SyncLock
    29.         ms.Close()
    30.     End Sub
    Upon the image being Received, the DataReceived Event event will be raised.
    Hope you enjoy it and find it useful. As i am an amateur, suggestions of how I can improve the code is appreciated.
    Last edited by Zapper; Sep 20th, 2008 at 03:16 AM.

  40. #40
    New Member
    Join Date
    Feb 2009
    Posts
    2

    Re: Client/Server Socket classes for file transfer

    Thanks to Mr Moeur for this flexible piece of code. I believe I have discovered why the application crashes when a connection is lost. It is due to System.Net.Sockets.SocketError.ConnectionAborted() error. I have not figured out how to capture this error and raise the error to other class files.

    I stumbled upon this condition when toggling the AllowConnection from true to false during code execution.

    I resolved this issue by adding the following "Requestor.Client.Disconnect(True)" to the Listener_ConnectionRequest method

    vb Code:
    1. Private Sub Listener_ConnectionRequest(ByVal Requestor As System.Net.Sockets.TcpClient, ByRef AllowConnection As Boolean) Handles Listener.ConnectionRequest
    2.         AllowConnection = CheckBox1.Checked
    3.      
    4.         If AllowConnection = False Then
    5.                  Requestor.Client.Disconnect(True)
    6.         End If
    7.  
    8.     End Sub

    As I can best understand it the Requestor.Client.Disconnect(True) allows for a graceful disconnection to the Socket that the TCPClient that has initiated the connection. I hope that this helps some one else.

    You will have to stop and start the listener again in order to accept connections if you stop allowing connections.

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