Click here to Skip to main content
15,891,033 members
Articles / Programming Languages / Visual Basic

Building a UDP Client/Server application in VB.NET

Rate me:
Please Sign up or sign in to vote.
4.14/5 (4 votes)
26 Apr 20069 min read 100.2K   8.1K   42  
This article describes a possible way to manage your UDP connections, along with some protocol suggestions and a working sample of UDP client/server application
Public Class UDPMaster
    Public Class DGram
        Public IP As String
        Public Port As Integer
        Public data As Byte()
        Public timeStamp As Long
        Public lastSendOut As Long
        Public sends As Integer
    End Class
    Shared enc As System.Text.Encoding = System.Text.Encoding.UTF8
    Shared localPort As Integer = 2002
    Shared udp As System.Net.Sockets.UdpClient
    Public RadioThread As Threading.Thread
    Public datagrams As New Queue
    Public lastError As String
    
    Function Send(ByRef Dgram As DGram) As Boolean
        Return Send(Dgram.IP, Dgram.Port, Dgram.data)
    End Function
    Function Send(Byref IP As String, ByVal port As Integer, ByVal data As String) As Boolean
        Return Send(IP, port, StringToBytes(data))
    End Function
    Function Send(ByVal IP As String, ByVal port As Integer, ByRef data As Byte()) As Boolean
        Dim bytCommand As Byte() = New Byte() {}
        Dim pRet As Integer

        Try
            bytCommand = data
            pRet = udp.Send(bytCommand, bytCommand.Length, IP, port)
            Return True
        Catch ex As Exception
            lastError = ex.Message
            'BetCon(ex.Message)
            Return False
        End Try
    End Function

    Sub SetUpRadio()
        If running Then
            RadioThread = New Threading.Thread(AddressOf Radio)
            RadioThread.Start()
        End If
    End Sub
    Sub Radio()
        'Do
        Try
            Dim remoteEP As System.Net.IPEndPoint = Nothing
            Dim rcvBytes As Byte() = udp.Receive(remoteEP)
            Dim rcvMsg As String = BytesToString(rcvBytes, UBound(rcvBytes))

            Dim xx As New DGram
            xx.IP = remoteEP.Address.ToString
            xx.Port = remoteEP.Port
            xx.data = rcvBytes
            xx.timeStamp = Environment.TickCount
            datagrams.Enqueue(xx)
        Catch e As Exception
            lastError = e.Message
            '          BetCon(e.Message)

        End Try
        'Loop

        SetUpRadio()
    End Sub
    Function HasNews() As Boolean
        If datagrams.Count > 0 Then Return True Else Return False
    End Function
    Function Poll(ByRef DG As DGram) As Boolean
        If datagrams.Count > 0 Then
            DG = datagrams.Dequeue
            Return True
        End If
        Return False
    End Function
    Sub New(Optional ByVal lp As Integer = 0)
        udp = New System.Net.Sockets.UdpClient(lp)
        localPort = lp
        SetUpRadio()
    End Sub
    Sub Dispose()
        udp.Close()
        udp = Nothing
        RadioThread.Abort()
    End Sub
    'Helper functions
    Public Shared Function StringToBytes(ByVal data As String) As Byte()
        Dim RetArr() As Byte
        Dim lenStr As Short = Len(data) - 1
        Dim i As Short
        ReDim RetArr(lenStr)
        For i = 0 To lenStr
            RetArr(i) = Asc(Mid$(data, i + 1, 1))
        Next i
        Return RetArr
    End Function
    Public Shared Function BytesToString(ByRef Data() As Byte, ByVal max As Short) As String
        ReDim Preserve Data(max)
        Dim i As Short, s As String
        For i = 0 To max
            s = s + Chr(Data(i))
        Next i
        Return s
    End Function
End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions