Need help with UDP listen!

touchsquid

Active Member
Licensed User
Longtime User
I'm writing code to connect with a Global Cache Itach. This device broadcasts a UDP packet on port 4998 once a minute. I know it is working because I wrote a windows app which picks up the UDP packet no problem.

Also, I can connect to the device through the browser on its TCP/IP port.

Anyway, here is the code I used to test it. This runs(on the Android tablet through B4A-Bridge) but UDP_PacketArrived never gets called.

'Activity module
Sub Process_Globals

Dim UDPSocket1 As UDPSocketEnd Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
If FirstTime Then
UDPSocket1.Initialize("UDP", 4998, 8000)
End If

End Sub

Sub UDP_PacketArrived (Packet As UDPPacket)
Dim msg As String
msg = BytesToString(Packet.Data, Packet.Offset, Packet.Length, "UTF8")
Msgbox("Message received: " & msg, "")
End Sub

Does anyone have an idea why this doesn't work? By the way, I am able to send UDP packets with B4A no problem.

Thanks to all you dedicated helpers online!
 

touchsquid

Active Member
Licensed User
Longtime User
I made a small error in the above code. It should be port 9131. However, it still doesn't works!
 
Upvote 0

touchsquid

Active Member
Licensed User
Longtime User
Tried that--no errors

Hi Erel,

I did as you suggest. There are no error messages.

This is the VB.NET code which works:

Sub UDPstart()
Dim t As New Threading.Thread(AddressOf listen)
t.IsBackground = True
t.Start()

End Sub

Sub UDPend()
If theSocket IsNot Nothing Then theSocket.Close()
If beaconSocket IsNot Nothing Then beaconSocket.Close()
End Sub
Private Sub listen()


theSocket.Bind(ipep)

Dim beaconEP As New IPEndPoint(IPAddress.Any, 9131)
beaconSocket.Bind(beaconEP)

Dim ip As IPAddress = IPAddress.Parse("239.255.250.250")
'Dim sendEP As New IPEndPoint(ip, 9132)

beaconSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, New MulticastOption(ip, IPAddress.Any))
Dim temp As String = ""

Try
Do
'Dim b() As Byte = beaconSocket.Receive(beaconEP)
Dim b(255) As Byte
beaconSocket.Receive(b)
temp = System.Text.Encoding.UTF8.GetString(b)
If temp <> "" Then
If ParseGCInfo(temp) Then 'get once at start up
Exit Do
End If
End If

Loop
Catch ex As Exception
theSocket.Close()
beaconSocket.Close()
End Try

End Sub

Function ParseGCInfo(args As String) As Boolean
' The beacon message has the following format:
'AMXB<-UUID=GlobalCache_000C1E024239><-SDKClass=Utility>
'<-Make=GlobalCache><-Model=iTachWF2IR><-Revision=700-1001-10>
'<-Pkg_Level=GCPK001><-Config-URL=http://192.168.1.100.><-PCB_PN=025-0026-06>
'<-Status=Ready>
If Not args.StartsWith("AMXB") Then 'not an itach
Return False
End If
Dim i As Integer = InStr(args, "http://")
If i > 0 Then
args = Right(args, Len(args) - i - 6)
Dim j As Integer = InStr(args, ">")
ITACH_IP = Left(args, j - 1)
Return True
Else
Return False
End If
End Function
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
I've attached an example written for Basic4ppc by agraham. It creates a server that listens for packets and sends a reply.
The executable is included so you can just run it.

I've tested it with this code and it works fine, the reply message is received:
B4X:
Sub process_globals
    Dim UDPSocket1 As UDPSocket
End Sub

Sub Globals

End Sub
Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        UDPSocket1.Initialize("UDP", 0, 8000)
    End If
    Dim Packet As UDPPacket
    Dim data() As Byte
    data = "Hello from Android".GetBytes("UTF8")
    Packet.Initialize(data, "192.168.1.100", 5000)
    UDPSocket1.Send(Packet)
End Sub

Sub UDP_PacketArrived (Packet As UDPPacket)
    Dim msg As String
    msg = BytesToString(Packet.Data, Packet.Offset, Packet.Length, "UTF8")
    Msgbox("Message received: " & msg, "")
End Sub

Make sure to change the IP and port as needed.
 

Attachments

  • NetUDPserverDemo.zip
    18.6 KB · Views: 464
Upvote 0

agraham

Expert
Licensed User
Longtime User
Upvote 0

agraham

Expert
Licensed User
Longtime User
You could try the following code using the Reflection library to allow reception of multicast packets. Note the warning in the MulticastLock link above "Processing these extra packets can cause a noticable battery drain and should be disabled when not needed".

You need to add the following permission to the manifext and make it read-only.
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
B4X:
Dim Obj1 As Reflector
Obj1.Target = Obj1.GetContext
Obj1.Target = Obj1.RunMethod2("getSystemService", "wifi", "java.lang.String")
Obj1.Target = Obj1.RunMethod2("createMulticastLock", "mylock", "java.lang.String")
Obj1.RunMethod2("setReferenceCounted", False, "java.lang.boolean") ' not really necessary but safer

' needs <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
Obj1.RunMethod("acquire")

' release when not needed to save battery   
Obj1.RunMethod("release")
 
Upvote 0

touchsquid

Active Member
Licensed User
Longtime User
This is the correct answer. I'm not sending multicasts, just receiving. We got it working today by using a Java library which sets the permissions and enables multicasts for 1 minute which is all we need. I got a local Java programmer to do it in just a few hours. Thanks for all the ideas.
 
Upvote 0

Kevin

Well-Known Member
Licensed User
Longtime User
I know this is an old thread, but I was wondering if you could share your solution to listening for the iTach? I am trying to do the exact same thing and I can't seem to pick up the packets at all. My code is almost identical to the samples above and I also tried AGraham's suggestion on using reflection and the multicast permission.

Or if anyone else has ever been successful in listening on a particular port using UDP, I'd appreciate any ideas.

Like touchsquid, I am able to send UDP packets (such as MSEARCH) and can even receive responses from it, but simply trying to listen to the iTach beacon packets sent to 239.255.250.250 at port 9132 doesn't seem to be working.
 
Upvote 0

touchsquid

Active Member
Licensed User
Longtime User
I know this is an old thread, but I was wondering if you could share your solution to listening for the iTach? I am trying to do the exact same thing and I can't seem to pick up the packets at all. My code is almost identical to the samples above and I also tried AGraham's suggestion on using reflection and the multicast permission.

Or if anyone else has ever been successful in listening on a particular port using UDP, I'd appreciate any ideas.

Like touchsquid, I am able to send UDP packets (such as MSEARCH) and can even receive responses from it, but simply trying to listen to the iTach beacon packets sent to 239.255.250.250 at port 9132 doesn't seem to be working.

Library attached. I have had trouble getting it to work reliably, so our app now does a search (for multiple itachs) by trying to connect on all LAN ips between 2 and 255 and recording results when an itach is found. It takes about 60 seconds, the same as the maximum wait time for the UDP packet but seems more reliable.
 

Attachments

  • GCTS.zip
    6.4 KB · Views: 276
Upvote 0

Kevin

Well-Known Member
Licensed User
Longtime User
Thanks! I'll check it out. I considered sending a request to all possible IP addresses but figured this would be better. If I experience problems with it too then I suppose I'll just send the requests out like you are doing.
 
Upvote 0

PD5DJ

Member
Licensed User
Longtime User
Hi Erel,

Can you give us (me) an example how to receive a packet that is on another port then the transmitting part?

For example, i am now sending packets (strings) via port 12000..
But for receiving i want to listen to port 12001 simultaniously

How should i approach this?? do you have any example?

Bjorn de PD5DJ
 
Upvote 0

merlin2049er

Well-Known Member
Licensed User
Longtime User
I'm getting an error trying to start this little udp server...

"only one usage of each socket... continue?" I can't get it running :(
 
Upvote 0
Top