App that communicates itself by UDP, each side can send and receieve data async.
And connection is closed when the settings are needed (port or other).
And sometimes this error (Address already in use) - stops all the work
How to reuse the address that was firstly used successfully by the app automatically?
Sorry, Erel, unclear
One device with single app is a sensor mode, another is data receiver mode (the same app) and remote calibration. So, each device must be able to send data. If different port numbers on both devices - no data exchange, for sure.
But if to disconnect the connection for settings or any other reason - at second connection try this error occurs. If stop\start again - somethimes it helps, but sometimes - no, this error is shown.
Sub Start_UDP
Try
UDP.Close
Catch
Log("Start_UDP.Close:" & LastException)
End Try
Try
If UDP.IsInitialized = False Then
UDP.Initialize("UDP", prefs.manager.GetString("PortNumber"),1000)
End If
timUDP.Enabled = True
Catch
Dim a As ServerSocket
a.Initialize(prefs.manager.GetString("PortNumber"), "")
Dim s As String = "WiFi error: " & a.GetMyWifiIP & ": " & LastException
others.Notif(s, False, True, Me, "")
Log(s)
ToastMessageShow(s, True)
End Try
End Sub
at Service.Start and at
B4X:
Sub ph_ConnectivityChanged (NetworkType As String, State As String, Intent As Intent)
If State = "CONNECTED" Then
others.Notif("Internet OK", False, False, Main, "")
InternetConnected = True
Start_UDP
Else 'NO INTERNET
InternetConnected = False
a = "Check WiFi-connection..."
others.Notif(a, False, False, Main, "")
ToastMessageShow(a, True)
UDP.Close
End If
End Sub
Sure. My single app has setting: sensor or receiver, common the same port and these UDP subs above.
Sensor sends data, receiver gets. Receiver gives command to calibrate the sensor and gets delta values for calibration.
Encountered a similar problem, and found this thread. Starting UDP in Starter.bas and keep it open works, but the UDP_PacketArrived can only be placed (works only) in Starter.bas. Now, I do an UDP-start in each module (in the Resume and an UDP-close in the Pause. Each module can transmit and receive it's data.
Assuming, I am the only Android client of my esp8266 server Details:
Sub Process_Globals : Public IPserver As String = "192.168.1.34"
Private UDPSock As UDPSocket : Private Packet As UDPPacket etc
Sub Activity_Resume : UDPSock.Initialize("UDP", 6000, 256) etc
Sub Activity_Pause (UserClosed As Boolean) : UDPSock.Close etc
Sub UDP_PacketArrived (Packetx As UDPPacket)
Msgbox(Packetx.Data(0) & etc
What a nice solution via Starter.bas, CallSub and CallSubDelayed. Better than the vb.net mechanism (with Delegate and InvokeRequired for a non-gui thread/backgroundworker). Thank you!