Note that the extra lines in your code makes it difficult to read the code.
1. Why are you using CallSub to call a sub in the current modules?
2. You haven't posted the code in PrintBuffer. Does it send data with AStream.Write? It is an asynchronous method. Don't close the connection immediately.
PrintBuffer(...)
astream.SendAllAndClose
'the Terminated event will be raised when the connection is closed
1. Yes: PrintBuffer calls SendData (Buffer.GetBytes(...)) than astream.Write.
I'm using "CallSubDelayed (Me, "Disconnect")" because I want to ensure that the disconnect sub will be called only after the astream.Write method has finished to send the whole buffer to the target connected device (probably I'm wrong).
CallSubDelayed IDE help says: "The sub will be called when the message is processed. This is useful in cases where you want to do something "right after" the current sub...
So you are telling me that I have to wait for the astream_Teminated event and only within this event I can call "Disconnect" Sub?
Otherwise my posted code (post #2 - 1. Doubt1) could introduce bugs when I send the buffer to the connected target device ?
Instead of astream.Write(data) I have to use astream.SendAllAndClose?
Or I have to call the astream.SendAllAndClose just after the PrintBuffer?
In this case all the PrintBuffer and SendData code remain the same. Correct?
If the second case is correct, which return flag I have to check to ensure that the write was executed successfully (both) ?
StreamWriteOK = astream.Write(data)
StreamWriteOK1 = astream.SendAllAndClose
Public Sub SendData (data() As Byte)
If connected Then
StreamWriteOK = astream.Write(data)
Log ("StreamWriteOK = " & StreamWriteOK)
End If
End Sub
Sub PrintBuffer (Buffer As String)
SendData (Buffer.GetBytes("UTF8"))
End Sub
So the _Teminated event should be ...
Sub AStream_Terminated
UpdateState(False)
Disconnect
End Sub