I developed this code to continuosly triying to connect to a server until the connection is OK. If it fails the loops continues.
In few words, the code every 4 seconds tries to connect to a server if it isn't connected. If it is connected it sends a query to the server and waits for 2 seconds a reply. If it doesn't come it closes astream and socket1 and restart trying to connect.
The first connection is ok. If after a succesful connection I stop the server, when I restart the server the code writes TWO times "Connected" and often it crashes.
It crashes in : astream.InitializePrefix(Socket1.InputStream, False, Socket1.OutputStream, "astream")
May be that someone knows why ?
Thank you.
B4X:
Sub Activity_Create(FirstTime As Boolean)
'Do not forget to load the layout file created with the visual designer. For example:
Activity.LoadLayout("1")
If FirstTime Then
connectiontimer.Initialize("connectiontimer",4000)
connectiontimer.Enabled = True
timeoutTimer.Initialize("timeoutTimer",2000)
timeoutTimer.Enabled=False
End If
Log("aaaaa")
End Sub
Sub connectiontimer_tick
If Socket1.IsInitialized Then
If Socket1.Connected=False Then
Socket1.Close
Socket1.Initialize("Socket1")
Socket1.Connect("192.168.1.11", 17178, 2000)
Else
send_data("STATUS")
timeoutTimer.Enabled=True
End If
Else
Socket1.Initialize("Socket1")
Socket1.Connect("192.168.1.11", 17178, 2000)
End If
End Sub
Sub timeoutTimer_tick
astream.Close
Socket1.Close
End Sub
Sub astream_Error
End Sub
Sub astream_Terminated
End Sub
Sub Socket1_Connected (Successful As Boolean)
If Successful = False Then
ToastMessageShow("Error Connecting",False)
Socket1.Close
Return
End If
ToastMessageShow("Connected",False)
astream.InitializePrefix(Socket1.InputStream, False, Socket1.OutputStream, "astream")
Dim buffer() As Byte
buffer = "CIAOAAA".GetBytes("UTF8")
astream.Write(buffer)
End Sub
Sub astream_NewData (Buffer() As Byte)
msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
timeoutTimer.Enabled=False
If oldMsg<>msg Then
..... ......
End If
End Sub
Sub send_data(data As String)
Dim buffer() As Byte
buffer = data.GetBytes("UTF8")
astream.Write(buffer)
End Sub
In few words, the code every 4 seconds tries to connect to a server if it isn't connected. If it is connected it sends a query to the server and waits for 2 seconds a reply. If it doesn't come it closes astream and socket1 and restart trying to connect.
The first connection is ok. If after a succesful connection I stop the server, when I restart the server the code writes TWO times "Connected" and often it crashes.
It crashes in : astream.InitializePrefix(Socket1.InputStream, False, Socket1.OutputStream, "astream")
May be that someone knows why ?
Thank you.