VB.Net TCP Client/Server-VBForums
Results 1 to 16 of 16

Thread: VB.Net TCP Client/Server

  1. #1

    Thread Starter
    New Member
    Join Date
    Feb 2008
    Posts
    2

    VB.Net TCP Client/Server

    Hello,

    I am very new to vb.net and I would like to know/learn how to make a basic client/server with whatever vb.net uses. I recently decided to convert from vb6 and I was using Winsock before, and now have decided to convert over to vb.net as vb6 wont be supported in the future, and a lot of the applications in vb6 don't work very well with Vista.

    All I am looking for is a simple server that will listen for the incoming connection from the client, and then a client where all you do is push 1 button and it will send a test packet back to the server. I just need a very basic setup with no extra code just to see how it works.

    Could someone please help me?
    Thank you very much,
    -3xpl0it

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

    Re: VB.Net TCP Client/Server

    Basically the two classes you need to look at are System.Net.Sockets.TcpClient and System.Net.Sockets.TcpClient.
    Follow the link in my signature for an example on a pretty basic server/client solution.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3

    Thread Starter
    New Member
    Join Date
    Feb 2008
    Posts
    2

    Re: VB.Net TCP Client/Server

    Hello,

    I looked around at that, but is there something even more basic? I just want the bare minimum amount of code to get this to work, so I know what I need and can build on just that base code. This will be my first major network project in vb.net, and I am very used to winsock like I said, so I am very lost... Could you help me with this/explain what each piece is for so I know what it is actually doing?

    Thanks in advance!
    -3xpl0it
    Last edited by 3xpl0it; Feb 23rd, 2008 at 08:29 PM.

  4. #4
    Lively Member
    Join Date
    May 2007
    Posts
    87

    Re: VB.Net TCP Client/Server

    Well network programming isnt easy.

    However its much better(for yourself too) to use the socket classes and understand how it works this way you can find/track/solve bugs much easier.

    http://www.vwsoftwaresolutions.nl/winsock2005.dll.zip

    That is the winsock.net component wich is basicly just a wraper around the system.net.sockets.socket class.

    Its perfect for small projects but if you have a 'major' project and if i were you i should create my own code for your projects purpose only.

    Greets

  5. #5
    New Member
    Join Date
    Jun 2009
    Posts
    15

    Re: VB.Net TCP Client/Server

    I'm not understanding the whole mutlithreading and use of Invoke()... How would I use Me.Close() within messageReceived() on the client side?

    Great share by the way, I literally just started looking into VB.NET yesterday and I've learned a lot by playing with your code Atheist.

    Thanks

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

    Re: VB.Net TCP Client/Server

    Hey Phaaze and welcome to VBForums.
    Since the messageReceived method will be executed on the worker thread that handles the incoming messages, you can not directly call a method on the form (such as Me.Close) from it, since you need to access forms and controls on the same thread as the one on which they where created.
    This is why we use the Invoke method, which will execute the given method on the same thread that created the control we call it on. So in your case this would be the way:

    Code:
    Private Sub CloseForm()
        If Me.InvokeRequired Then
            Me.Invoke(New MethodInvoker(AddressOf CloseForm))
        Else
            Me.Close()
        End If
    End Sub
    You can call this method from anywhere. If the currently executing thread is the "correct" one (that is, it is the thread that created the form that 'Me' refers to), the InvokeRequired property will return false and Me.Close will be invoked. If however InvokeRequired returns true, there will be a call to Me.Invoke, which will call the CloseForm method again, but this time, InvokeRequired will return false, and Me.Close will be invoked.
    ---My Flickr photo (mostly screenshots these days!) stream. Have a look!

    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    TCP client/server connection | Retrieving the EventHandler for any Event by code.
    Me on.. BitBucket, Google Code, Github (pretty empty)

  7. #7
    New Member
    Join Date
    Jun 2009
    Posts
    15

    Re: VB.Net TCP Client/Server

    Thank you Atheist, I had just figured out the code I needed prior to reading your post but the explanation has helped greatly.

    Furthermore, how are you supposed to handle client disconnections? I know I can send some sort of keepalive message to the server but I'm talking about when the client is closed, the server just crashes. How can I prevent the server from crashing?

    Edit: I figured out I can use
    Code:
    If mClient.GetStream.DataAvailable Then
    prior to
    Code:
    bytesRead = mClient.GetStream.Read(readBuffer, 0, BYTES_TO_READ)
    and it prevents the server from crashing.

    Thanks again for sharing this with us Atheist! This is a great example to learn from.


    Edit 2: How can I get the clients IP Address? Also, how can I call a function in the Form1 class from the ConnectedClient class on the server?
    Last edited by Phaaze; Jun 12th, 2009 at 02:18 PM.

  8. #8
    New Member
    Join Date
    Sep 2009
    Posts
    4

    Re: VB.Net TCP Client/Server

    EDIT: oops... wrong thread sorry
    Last edited by fredfish; Sep 21st, 2009 at 07:30 AM.

  9. #9
    New Member
    Join Date
    Feb 2012
    Posts
    2

    Re: VB.Net TCP Client/Server

    I am also new to vb. I am trying to write a program to monitor a port and write the data to an access table. I am not sure where to start; how I can test any code that I begin writing.

  10. #10
    Hyperactive Member
    Join Date
    Oct 2004
    Posts
    259

    Re: VB.Net TCP Client/Server

    MR. Lastly, welcome to the board.
    please start a new thread of your own rather than taking someone elses.

    Also, since you are new to VB let us know what other programing experience you have when you start your new thread. it will help us better vocalize an answer for you.
    ----------------------------------------------------

    Missing the days of GWBasic 1.1
    WaxyStudios.com

  11. #11
    New Member
    Join Date
    Feb 2012
    Posts
    1

    Re: VB.Net TCP Client/Server

    Quote Originally Posted by ovanwijk View Post
    Well network programming isnt easy.

    However its much better(for yourself too) to use the socket classes and understand how it works this way you can find/track/solve bugs much easier.

    http://www.vwsoftwaresolutions.nl/winsock2005.dll.zip

    That is the winsock.net component wich is basicly just a wraper around the system.net.sockets.socket class.

    Its perfect for small projects but if you have a 'major' project and if i were you i should create my own code for your projects purpose only.

    Greets
    Can you provide some example programs for reference? I am new to client/server program in VB.net.

  12. #12
    Hyperactive Member
    Join Date
    Oct 2004
    Posts
    259

    Re: VB.Net TCP Client/Server

    Quote Originally Posted by ovanwijk View Post
    Well network programming isnt easy.

    However its much better(for yourself too) to use the socket classes and understand how it works this way you can find/track/solve bugs much easier.

    http://www.vwsoftwaresolutions.nl/winsock2005.dll.zip

    That is the winsock.net component wich is basicly just a wraper around the system.net.sockets.socket class.

    Its perfect for small projects but if you have a 'major' project and if i were you i should create my own code for your projects purpose only.

    Greets
    Does it provide some way to allow UDP traffic inbound? that's been my greatest problem. not all routers are UPNP enabled. so far my biggest clue for how big business games get around router configurations has been UDP Hole Punching.
    ----------------------------------------------------

    Missing the days of GWBasic 1.1
    WaxyStudios.com

  13. #13
    New Member
    Join Date
    Mar 2012
    Posts
    1

    Re: VB.Net TCP Client/Server

    hello.. may i...
    i just new to vb..
    how can i make an application such as LAN messengger that use client/server function?
    where does i need to start?
    can anyone guide me... i'm very lost..

  14. #14
    New Member
    Join Date
    Aug 2012
    Posts
    8

    Re: VB.Net TCP Client/Server

    Hello. I am trying to implement this for a simple server that would have multiple clients and will serve 5 weather parameters in one tab-delimited string. Connection and sending data is no problem, however, I am having problems with a memory leak and with disposing of disconnected clients. The removeClient subroutine does not really get rid of the client because I've noticed that doRead continues to execute even after the client disconnects. My CPU usage jumps to 100% when a client disconnects. In addition, the memory usage rises by about 8kB/s when it is running. I've tried setting up a Dispose call, but even after this call doRead continues to run. In my normal application I don't ever need to get rid of objects under execution is over. Any ideas?

    Server Form
    Code:
    Imports System.Net.Sockets
    Imports System.Threading
    Public Class frmServerMain
        Private VaisalaDevice As Vaisala
    
        Private listener As System.Net.Sockets.TcpListener
        Private listenThread As System.Threading.Thread
    
        Private tmrWrite As Timer
        Private TimerWriteDelegate As TimerCallback
    
        Private Open As Boolean
    
        Private clients As New List(Of ConnectedClient) 'This list will store all connected clients.
    
        Private Sub frmServerMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 43001) 'The TcpListener will listen for incoming connections at port 43001
            listener.Start() 'Start listening.
            listenThread = New System.Threading.Thread(AddressOf doListen) 'This thread will run the doListen method
            listenThread.IsBackground = True 'Since we dont want this thread to keep on running after the application closes, we set isBackground to true.
            listenThread.Start() 'Start executing doListen on the worker thread.
    
            ' Write to the port 4 times per second.
            TimerWriteDelegate = AddressOf SendMessage
            tmrWrite = New System.Threading.Timer(TimerWriteDelegate, Open, 0, 1000)
        End Sub
    
        Private Sub doListen()
            Dim incomingClient As System.Net.Sockets.TcpClient
            Do
                incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
                Dim connClient As New ConnectedClient(incomingClient, Me) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
                AddHandler connClient.dataReceived, AddressOf Me.messageReceived
                clients.Add(connClient) 'Adds the connected client to the list of connected clients.
                Control.CheckForIllegalCrossThreadCalls = False
                connClient.Username = incomingClient.Client.RemoteEndPoint.ToString
                ListBox1.Items.Add(connClient.Username & " connected.")
            Loop
        End Sub
        Public Sub SendMessage()
            For Each cc As ConnectedClient In clients
                cc.SendMessage("this is a test")
            Next
        End Sub
        Public Sub removeClient(ByVal client As ConnectedClient)
            If clients.Contains(client) Then
                clients.Remove(client)
                client.Dispose()
                ListBox1.Items.Remove(client.Username & " connected.")
            End If
        End Sub
    
        Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
            'A message has been received from one of the clients.
            'To determine who its from, use the sender object.
            'sender.SendMessage can be used to reply to the sender.
    
            Dim data() As String = message.Split("|"c) 'Split the message on each | and place in the string array.
            Select Case data(0)
                Case "CONNECT"
                    'We use GetClientByName to make sure no one else is using this username.
                    'It will return Nothing if the username is free.
                    'Since the client sent the message in this format: CONNECT|UserName, the username will be in the array on index 1.
                    If GetClientByName(data(1)) Is Nothing Then
                        'The username is not taken, we can safely assign it to the sender.
                        sender.Username = data(1)
                    End If
                Case "DISCONNECT"
                    removeClient(sender)
            End Select
    
        End Sub
    
        Private Function GetClientByName(ByVal name As String) As ConnectedClient
            For Each cc As ConnectedClient In clients
                If cc.Username = name Then
                    Return cc 'client found, return it.
                End If
            Next
            'If we've reached this part of the method, there is no client by that name
            Return Nothing
        End Function
    
    
    End Class
    ConnectedClient Class
    Code:
    Public Class ConnectedClient
        Implements IDisposable
        Private mClient As System.Net.Sockets.TcpClient
    
        Private mUsername As String
        Private mParentForm As frmServerMain
        Private readThread As System.Threading.Thread
        Private Const MESSAGE_DELIMITER As Char = ControlChars.Cr
        Protected disposed As Boolean = False
    
        Public Event dataReceived(ByVal sender As ConnectedClient, ByVal message As String)
    
        Sub New(ByVal client As System.Net.Sockets.TcpClient, ByVal parentForm As frmServerMain)
            mParentForm = parentForm
            mClient = client
    
            readThread = New System.Threading.Thread(AddressOf doRead)
            readThread.IsBackground = True
            readThread.Start()
        End Sub
    
        Public Property Username() As String
            Get
                Return mUsername
            End Get
            Set(ByVal value As String)
                mUsername = value
            End Set
        End Property
    
        Private Sub doRead()
            Const BYTES_TO_READ As Integer = 255
            Dim readBuffer(BYTES_TO_READ) As Byte
            Dim bytesRead As Integer
            Dim sBuilder As New System.Text.StringBuilder
            Do
                Try
                    If mClient.Connected Then
                        bytesRead = mClient.GetStream.Read(readBuffer, 0, BYTES_TO_READ)
                        If (bytesRead > 0) Then
                            Dim message As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, bytesRead)
                            If (message.IndexOf(MESSAGE_DELIMITER) > -1) Then
    
                                Dim subMessages() As String = message.Split(MESSAGE_DELIMITER)
    
                                'The first element in the subMessages string array must be the last part of the current message.
                                'So we append it to the StringBuilder and raise the dataReceived event
                                sBuilder.Append(subMessages(0))
                                RaiseEvent dataReceived(Me, sBuilder.ToString)
                                sBuilder = New System.Text.StringBuilder
    
                                'If there are only 2 elements in the array, we know that the second one is an incomplete message,
                                'though if there are more then two then every element inbetween the first and the last are complete messages:
                                If subMessages.Length = 2 Then
                                    sBuilder.Append(subMessages(1))
                                Else
                                    For i As Integer = 1 To subMessages.GetUpperBound(0) - 1
                                        RaiseEvent dataReceived(Me, subMessages(i))
                                    Next
                                    sBuilder.Append(subMessages(subMessages.GetUpperBound(0)))
                                End If
                            Else
    
                                'MESSAGE_DELIMITER was not found in the message, so we just append everything to the stringbuilder.
                                sBuilder.Append(message)
                            End If
                        End If
                    Else
                        mParentForm.removeClient(Me)
    
                        'Exit Do
                    End If
                Catch ex As Exception
    
                End Try
            Loop
        End Sub
    
        Public Sub SendMessage(ByVal msg As String)
            Dim sw As IO.StreamWriter
            Try
                SyncLock mClient.GetStream
                    sw = New IO.StreamWriter(mClient.GetStream) 'Create a new streamwriter that will be writing directly to the networkstream.
                    sw.Write(msg)
                    sw.Flush()
                End SyncLock
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
            'As opposed to writing to a file, we DONT call close on the streamwriter, since we dont want to close the stream.
        End Sub
        Protected Overridable Overloads Sub Dispose( _
                    ByVal disposing As Boolean)
            If Not Me.disposed Then
                If disposing Then
                    'managedResource.Dispose()
                End If
                ' Add code here to release the unmanaged resource.
                'unmanagedResource = IntPtr.Zero
                ' Note that this is not thread safe.
            End If
            Me.disposed = True
        End Sub
    
    #Region " IDisposable Support "
        ' Do not change or add Overridable to these methods.
        ' Put cleanup code in Dispose(ByVal disposing As Boolean).
        Public Overloads Sub Dispose() Implements IDisposable.Dispose
            Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub
        Protected Overrides Sub Finalize()
            Dispose(False)
            MyBase.Finalize()
        End Sub
    #End Region
    End Class

  15. #15
    New Member
    Join Date
    Sep 2012
    Posts
    2

    Re: VB.Net TCP Client/Server

    Error 1 Type 'Vaisala' is not defined. F:\Projects\AMRSyncTcp\Server\Server\frmServerMain.vb 4 30 Server

  16. #16
    New Member
    Join Date
    Aug 2012
    Posts
    8

    Re: VB.Net TCP Client/Server

    Quote Originally Posted by dimasiano View Post
    Error 1 Type 'Vaisala' is not defined. F:\Projects\AMRSyncTcp\Server\Server\frmServerMain.vb 4 30 Server
    Comment out any reference to Vaisala as it will not work unless you have that instrument.

Posting Permissions

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



Featured


Click Here to Expand Forum to Full Width

Survey posted by VBForums.