Confusing issue with Sockets and Asyncstreams

jbertman

New Member
I've been reading these forums for a long time and I haven't been able to find an answer to my problem, so I was hoping someone could help me out.

I'm writing a very simple socket communication app. All it needs to do is send and receive text. I have a server written in VB outside of B4A running under Windows. It is the server written by MSDN called Asynchronous Server Socket Example. The problem I'm having is with the client (Android).

Client Code:
B4X:
Sub Process_Globals
    Dim Socket1 As Socket
   Dim AStreams As AsyncStreams
End Sub

Sub Globals
   Dim Button1 As Button
   Dim EditText1 As EditText
End Sub 

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("Layout1")
    Socket1.Initialize("Socket1")
    Socket1.Connect("192.168.1.21", 12345, 10000)
End Sub
Sub Socket1_Connected (Successful As Boolean)
   If Successful Then
        ToastMessageShow("Connected!", False)
        AStreams.Initialize(Socket1.InputStream, Socket1.OutputStream, "AStreams")
    Else
        ToastMessageShow("Error while connecting!", False)
    End If
End Sub
Sub AStreams_NewData (Buffer() As Byte)
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    ToastMessageShow(msg, False)
    Log("Received: " & msg & " from the server")
End Sub

Sub Button1_click
   Log("AStreams Status Pre-send: " & AStreams.IsInitialized)
    If AStreams.IsInitialized = False Then Return
    If EditText1.Text.Length > 0 Then
        Dim buffer() As Byte
      Dim data As String
      data = EditText1.text & "<EOF>"
        buffer = data.GetBytes("UTF8")
      AStreams.Write(buffer)
        EditText1.SelectAll
        Log("Sending: " & EditText1.Text)
      Log("AStreams Status Post-send: " & AStreams.IsInitialized)
    End If
End Sub
Sub AStreams_Error
    ToastMessageShow(LastException.Message, True)
End Sub

Sub Activity_Pause(UserClosed As Boolean)
    If UserClosed Then
        Log("closing")
        AStreams.Close
        Socket1.Close
    End If
End Sub

I can connect and send data fine, as well as receive the echo from the server. The problem is that it can only do it ONCE. After the first time, my "AStreams" is no longer initialized (as per my log tests). If I try to initialize again, it throws a socket closed exception, which seems to be untrue because I've checked the socket status pre-send and post-send and they both return true for both socket1 being initialized and connected. The AStreams.IsInitialized returns false just after writing the buffer and before anything even begins the next time I click the send button. Any suggestions?

Thanks in advance.
 
Top