How to listen to a TCP port for broadcast?

Drache

Active member
Joined
Apr 8, 2006
Messages
26
Programming Experience
Beginner
I have an external program which broadcasts a string on localhost, port 2456 whenever a event occurs.

What I want to do is connect to and listen to this port and when a string is received save it to a variable so I can do something with it, I have tried searching the usual places, Google, vb forums, but all I can find is examples that can send AND receive data, all I want need to do is listen.

I have an inkling the solution would involve TCPclient but I know next to nothing about TCP to work it out for myself, If anyone can help me with the code or point me in the right direction it would really help me out.

Cheers.
 
UDP is used for broadcast (and multicast and unicast), TCP only support unicast. This can be an example of a Broadcast listener, waiting for messages in background thread, adding them safely to a listbox:
VB.NET:
Private Sub receiver_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
    Dim t As New Threading.Thread(AddressOf listen)
    t.IsBackground = True
    t.Start()
End Sub

Private Sub receiver_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles Me.FormClosing
    If udp IsNot Nothing Then udp.Close()
End Sub

Private udp As Net.Sockets.UdpClient
Private Sub listen()
    Try
        udp = New Net.Sockets.UdpClient(2456)
        udp.EnableBroadcast = True
        Dim ep As New Net.IPEndPoint(Net.IPAddress.Broadcast, 2456)
        Do
            Dim b() As Byte = udp.Receive(ep)
            Me.Invoke(safeAddText, System.Text.Encoding.UTF32.GetString(b))
        Loop
    Catch ex As Exception
        If udp IsNot Nothing Then udp.Close()
    End Try
End Sub

Private Delegate Sub delAddText(ByVal text As String)
Private safeAddText As New delAddText(AddressOf AddText)
Private Sub AddText(ByVal text As String)
    ListBox1.Items.Add(text)
End Sub
I case you (or others) want to test/verify here a "sender", sends text from a textbox when button clicked:
VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
    Dim udp As New Net.Sockets.UdpClient()
    udp.EnableBroadcast = True
    Dim ep As New Net.IPEndPoint(Net.IPAddress.Broadcast, 2456)
    Dim b() As Byte = System.Text.Encoding.UTF32.GetBytes(TextBox1.Text)
    udp.Send(b, b.Length, ep)
    udp.Close()
End Sub
 
Thankyou for your help

Thanks for all your help, without your help I would have been in a canoe without a paddle.


Cheers.
 
Back
Top