Android Question UDP send and receive

FreeWolF

Active Member
Licensed User
Longtime User
Hello, I have a new question:

I have to send a string of bytes to a board. The board have to reply to me with the same string (in bytes). I had tried the asyncstream object, but the data won't sent from my phone.
With UDP the data is sent.

I have used that example:

B4X:
Sub Process_Globals
'These global variables will be declared once when the application starts.
'These variables can be accessed from all modules.

End Sub

Sub Globals
'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.

Private Button1 As Button
Private Button2 As Button
Private EditText1 As EditText
Private EditText2 As EditText
Dim Socket1 As Socket
Dim Server As ServerSocket

Dim UDPSocket1 As UDPSocket

End Sub

Sub Activity_Create(FirstTime As Boolean)
'Do not forget to load the layout file created with the visual designer. For example:
'Activity.LoadLayout("Layout1")
Activity.LoadLayout("Main")

  If FirstTime Then
Server.Initialize(5555, "Server")
Server.Listen
ToastMessageShow(("MyIp = " & Server.GetMyIP),True)
End If

If FirstTime Then
  UDPSocket1.Initialize("UDP", 5555, 8000)
  End If

End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub Socket1_Connected (Successful As Boolean)

If Successful = True Then
ToastMessageShow("Connected (SOCKET)", False)
Else
ToastMessageShow("Error (SOCKET)", False)
End If

End Sub

Sub Button2_Click

Dim Packet As UDPPacket
  Dim data() As Byte
  data = "0x01,  0x08,  0x00,  0x00, 0x00,  0x00, 0xE0, 0x0B".GetBytes("UTF8")
  Packet.Initialize(data, "192.168.1.10", 5555)
  UDPSocket1.Send(Packet)

End Sub
Sub Button1_Click

Socket1.Initialize("Socket1")
Socket1.Connect("192.168.1.10", 5555, 10000)

End Sub

Sub Server_NewConnection (Successful As Boolean, NewSocket As Socket)

If Successful Then
ToastMessageShow("Connected (SERVER)", False)
Socket1 = NewSocket
Else
ToastMessageShow("Error (SERVER)", False)
End If

Server.Listen

End Sub

Sub UDP_PacketArrived (Packet As UDPPacket)
  Dim msg As String
  msg = BytesToString(Packet.Data, Packet.Offset, Packet.Length, "UTF8")
  EditText2.Text = msg
End Sub

With that code the phone send the string to the board. But the board don't reply anything.

How I have to wirte for send the packet in bytes to the board? Is correct my code?


And the sub Packetarrived is correct? I think yes....
 
Last edited:
Top