Other UDP-Sample

HansDieter

Member
Licensed User
Longtime User
The UDP-Sample in the docu to the jnetwork-library didn't work at all.
It is obviously a 1 to 1 copy from the docu for the network lirary for B4A.

Here is what i came up with:

B4X:
Sub Process_Globals
    Private Msgbox As Msgboxes
    Dim UDPSocket1 As UDPSocket
End Sub

Sub AppStart (Form1 As Form, Args() As String)
    UDPSocket1.Initialize("UDP", 5000, 8000)
    Dim Packet As UDPPacket
    Dim data() As Byte
    data = "Hello from RaspBerry".GetBytes("UTF8")
    Packet.Initialize(data, "localhost", 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.show("Message received: " & msg, "")
End Sub

It is to remark that UDPSocket.Initialize must use the real port number. 0 as documented and used in the sample didn't work for me neither on my windows development system nor on my raspberryPI.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I tested it with port 0 and it worked:
B4X:
Sub Process_Globals
   Dim us As UDPSocket
End Sub

Sub AppStart (Args() As String)
   us.Initialize("us", 0, 8192)
   Log(us.Port)
   StartMessageLoop
End Sub

Sub us_PacketArrived (Packet As UDPPacket)
   Log(Packet.Length)
End Sub

I've created another app that connects to the "random" port:
B4X:
Sub AppStart (Args() As String)
   Dim up As UDPPacket
   up.Initialize("aaa".GetBytes("UTF8"), "127.0.0.1", 61409) 'port should match part printed in the other app.
   Dim us As UDPSocket
   us.Initialize("us", 0, 0)
   us.Send(up)
   StartMessageLoop
End Sub
 
Upvote 0

HansDieter

Member
Licensed User
Longtime User
I tested it with port 0 and it worked:


I've created another app that connects to the "random" port:
Hi Erel,

that was my error. I first thought port 0 is something like an "catch all" for incomeing UDP-packets triggering the event procedure no matter what port was used.
After studying the other members of the UDPsocket object more closely and thinking what implications such a behavior would have i realised how it really worked.

Hans
 
Upvote 0
Top