B4J Question UDP conflict?

bdunkleysmith

Active Member
Licensed User
Longtime User
I've successfully used UDP in a very simple B4J app for several years to remotely trigger button click events in another B4J app. I wanted to expand this so that as well as triggering a button click in the B4J app, I wanted to trigger a button click in a B4A app.

Here is the relevant code:

B4X:
Sub Process_Globals

    Private Packet1, Packet2 As UDPPacket
    Private data1() As Byte
    Private data2() As Byte
    Private TxPort1 As Int = 3661 ' To PlayerBoard
    Private TxPort2 As Int = 3662 ' To Effects Controller
    Private UDPSocket1, UDPSocket2 As UDPSocket
    Private broadcastIP As String
    Private HostIPAddress As TextField

End Sub

Sub AppStart (Form1 As Form, Args() As String)
    MainForm = Form1
    MainForm.RootPane.LoadLayout("1") 'Load the layout file.
    MainForm.Title = title
    MainForm.Icon = fx.LoadImage(File.DirAssets,"IMG_41.gif")
    MainForm.Show
    imgBDS.SetImage(fx.LoadImage(File.DirAssets,"BDSConsulting.png"))
    ' Get client IP address
    Dim JO As JavaObject
    JO.InitializeStatic("java.net.InetAddress")
    Dim JO2 As JavaObject = JO.RunMethod("getLocalHost", Null)
    Dim objHostAddress As Object = JO2.RunMethod("getHostAddress", Null)
    Dim ip As String = objHostAddress
    ClientIPAddress.Text = "Client IP Address: " & ip
    HostIPAddress.Text = ip   
    Dim Port As Int = 3663
    UDPSocket1.Initialize("UDP", Port, 8000)
    Dim Port As Int = 3664
    UDPSocket2.Initialize("UDP", Port, 8000)
    broadcastIPCalc
End Sub

Sub btnPlayerIntros_Click
    data1 = "Intros".GetBytes("UTF8")
    Packet1.Initialize(data1, broadcastIP, TxPort1)
    UDPSocket1.Send(Packet1)
    data2 = "NBL1_Intro".GetBytes("UTF8")
    Packet2.Initialize(data2, broadcastIP, TxPort2)
    UDPSocket2.Send(Packet2)
End Sub

Sub broadcastIPCalc
    Dim partip As String = HostIPAddress.Text
    Dim x As Int = partip.LastIndexOf(".")
    partip = partip.SubString2(0, x)
    broadcastIP = partip & ".255"
End Sub

However it seems while the first packet is always sent and received successfully, the second packet (on a different port), is not always received.

Is there something fundamentally wrong with my code? Or because I'm using a broadcast IP address rather than specific IP addresses for the two separate devices running the B4J and B4A apps, is the second packet somehow consumed before reaching the intended B4A app? Would a small delay between UDP sends help?

In any case, I'd appreciate the comments from others more knowledgeable than me in regard to UDP.
 

bdunkleysmith

Active Member
Licensed User
Longtime User
I see I am initialising both sockets with the same "UDP" event name:

B4X:
    UDPSocket1.Initialize("UDP", Port, 8000)

    UDPSocket2.Initialize("UDP", Port, 8000)

But while I should have distinct event names, that would surely only affect received packet handling, which is not an issue.
 
Upvote 0
Top