Results 1 to 40 of 54

Thread: Client/Server Socket classes for file transfer

Threaded View

  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.

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